首页 文章

在AWS EC2 Ubuntu Ruby on Rails上使用mosquitto设置Paho Javascript客户端(MQTT)

提问于
浏览
1

我一直在尝试使用端口1883在我的AWS EC2服务器上设置MQTT代理 . 到目前为止,它与ruby-mqtt gem一起使用,但是我在使用Paho Javascript Client为网站设置时遇到了问题 .

到目前为止我做了什么:

Mosquitto

在我的AWS EC2实例上安装了mosquitto,它正在1883端口上运行和监听 . 我使用命令在本地订阅了一个主题

mosquitto_sub -h localhost -p 1883 -v -t 'topic1'

AWS EC2 Security Group

允许通过端口1883的流量(在tcp协议下)

Ruby on Rails

安装ruby-mqtt gem,并通过在rails console(开发环境)中运行以下代码测试mqtt工作

MQTT::Client.connect(ip_address_or_domain_name) do |c|
  c.publish('topic1', 'message to topic 1')
end

该消息显示在运行 mosquitto_sub 的终端中 .

Nginx

所有这些都是在没有任何Nginx配置文件配置的情况下完成的 .

Paho Client

所以我在我的本地计算机上启动了一个本地rails服务器,并在我的一个html视图上运行示例javascript片段 .

// Create a client instance
client = new Paho.MQTT.Client("mqtt.hostname.com", Number(1883), "", "clientId")

// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

// connect the client
client.connect({onSuccess:onConnect});


// called when the client connects
function onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  client.subscribe("topic1");
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "topic1";
  client.send(message);
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

// called when a message arrives
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}

但我无法联系 . 我在chrome开发者控制台中遇到的错误是:

WebSocket connection to 'ws://mqtt.example.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

我不知道这里有什么问题 . 非常感谢任何帮助!提前致谢!

1 回答

  • 1

    所以问题是Paho Javascript客户端声明 client 对象的参数必须是

    消息传递服务器的地址,作为完全限定的WebSocket URI,作为DNS名称或点分十进制IP地址 .

    因此,让它监听端口1883,这是mqtt的标准端口,将无法正常工作 .

    ruby-mqtt 按原样工作,因为它的参数被视为mqtt uri

    换句话说, Paho 通过 ws://host 连接,而 ruby-mqtt 通过 mqtt://host 连接 . 对于正确的端口,后者使用正确的协议(不确定这是否是正确的字)连接到端口1883 .

    所以 Paho 必须连接到可以使用websocket协议的另一个端口 .

    这是我的解决方案 .

    Mosquitto

    在支持websocket的情况下,版本必须至少为1.4 . 我将最后3行添加到默认的 mosquitto.conf 文件中 .

    # /etc/mosquitto/mosquitto.conf
    pid_file /var/run/mosquitto.pid
    
    persistence true
    persistence_location /var/lib/mosquitto/
    
    log_dest file /var/log/mosquitto/mosquitto.log
    
    include_dir /etc/mosquitto/conf.d
    
    port 1883
    
    listener 1884
    protocol websockets
    

    这为mosquitto打开了2个端口,分别订阅了2个不同的协议 .

    AWS Security Group

    允许通过端口1884的流量(在tcp协议下)

    Paho Client

    mqtt.hostname.com只更改客户端对象初始化的行

    client = new Paho.MQTT.Client("mqtt.hostname.com", Number(1884), "", "clientId")
    

相关问题