【发布时间】:2017-05-31 23:15:39
【问题描述】:
我正在尝试将 Paho JS 库连接到 Snap!允许通过 MQTT 协议与服务器通信,但不知何故 WebSockets 一直在我身上崩溃。
这是我使用的代码:
var wsbroker = "127.0.0.1";
var wsport = 9001;
console.log("Connecting to: ", wsbroker);
console.log("Connecting to port: ", Number(wsport));
client = new Paho.MQTT.Client(wsbroker, Number(wsport),"Snap");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
var client_options = {
onSuccess:onConnect,
onFailure:doFail
}
client.connect(client_options);
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Client connected...");
client.subscribe("/Navicula/test");
message = new Paho.MQTT.Message("CONNECTED");
message.destinationName = "/Navicula/test";
client.send(message);
}
function doFail(e){
console.log("I haz failed");
console.log(e);
}
// 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);
}
之前实现过mqttws31.min.js(使用了mqttws31.js但结果一样)。
我使用以下配置安装了 mosquitto 1.4.8:
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /var/run/mosquitto.pid
listener 1883 127.0.0.1 protocol mqtt
listener 9001 127.0.0.1 protocol websockets
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
JS 代码从 pythons SimpleHTTPServer 上的 html 文件运行,运行后总是在控制台中打印:
WebSocket connection to 'ws://127.0.0.1:9001/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
将此作为 onFail 函数的错误代码:
Object {invocationContext: undefined, errorCode: 7, errorMessage: "AMQJS0007E Socket error:undefined."}
在服务器端(mosquitto)我得到以下日志:
1496269205: mosquitto version 1.4.8 (build date Fri, 19 Feb 2016 12:03:16 +0100) starting
1496269205: Config loaded from myconf.conf.
1496269205: Opening ipv4 listen socket on port 1883.
1496269205: Opening ipv4 listen socket on port 9001.
1496269215: New connection from 127.0.0.1 on port 9001.
1496269215: Socket error on client <unknown>, disconnecting.
1496269215: New connection from 127.0.0.1 on port 9001.
1496269215: Socket error on client <unknown>, disconnecting.
1496269224: New connection from 127.0.0.1 on port 9001.
1496269224: Socket error on client <unknown>, disconnecting.
1496269224: New connection from 127.0.0.1 on port 9001.
1496269224: Socket error on client <unknown>, disconnecting.
所以我想这一定是代码部分的某个地方有问题,但我完全迷失了这里。
【问题讨论】:
标签: javascript websocket mqtt mosquitto