我一直在尝试使用端口1883在我的AWS EC2服务器上设置MQTT代理。到目前为止,它适用于ruby-mqtt gem,但是我无法使用Paho Javascript客户端进行设置网站。
到目前为止我做了什么:
Mosquitto
在我的AWS EC2实例上安装了mosquitto,它正在运行并侦听端口1883.我使用命令在本地订阅了一个主题
mosquitto_sub -h localhost -p 1883 -v -t 'topic1'
AWS EC2安全组
允许通过端口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客户
所以我在本地计算机上启动了一个本地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
我不确定这里有什么问题。非常感谢任何帮助!提前谢谢!
答案 0 :(得分: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种不同的协议。
AWS Security Group
允许通过端口1884(在tcp协议下)的流量
Paho客户
mqtt.hostname.com 只更改客户端对象初始化的行
client = new Paho.MQTT.Client("mqtt.hostname.com", Number(1884), "", "clientId")