这是我的paho
客户端代码
// Create a client instance
client = new Paho.MQTT.Client('127.0.0.1', 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("/World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
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);
}
在Rabbitmq
服务器上,一切都是默认的seetings。当我运行此代码时,我得到WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Connection closed before receiving a handshake response
我缺少什么?
答案 0 :(得分:1)
问题尚不清楚,但我假设您在网络浏览器中运行上述代码。
这将通过Websockets建立MQTT连接(如错误中所示)。这与TCP连接上的本机MQTT不同。
默认的纯MQTT端口(如果是1883),Websocket支持可能位于不同的端口上。
您将需要配置RabbitMQ以接受基于Websockets的MQTT以及纯MQTT,此pull请求RabbitMQ接口以讨论添加此功能。它提到此功能仅在版本3.6.x中添加,并且文档仍然未完成(截至2016年2月9日)
答案 1 :(得分:1)
根据我在Windows上使用Paho MQTT JavaScript库和RabbitMQ代理的个人经验,这里列出了从浏览器中使用JS中的MQTT所需要做的事情:
client = new Paho.MQTT.Client("localhost", 15675, "/ws", "client-1");
//set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
//connect the client
client.connect({
onSuccess : onConnect
});
//called when the client connects
function onConnect() {
console.log("Connected");
}
//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);
}