我在Chrome中运行的SPA中使用paho-mqtt库,并使用示例代码调用连接,并收到两个交替错误
var client = mqtt.connect('mqtts:mqtt.ably.io', {
keepalive: 30,
username: 'keyPartA1.artA2',
password: 'keyPartB',
port: 8883
});
错误重复,并不总是以相同的顺序...
stream.js?553e:64 WebSocket connection to 'ws://mqtt.ably.io:8883/' failed: Connection closed before receiving a handshake response
WebSocketStream @ stream.js?553e:64
createWebSocket @ ws.js?fcb9:59
buildBuilderBrowser @ ws.js?fcb9:85
wrapper @ index.js?e7fc:148
MqttClient._setupStream @ client.js?df86:263
MqttClient._reconnect @ client.js?df86:847
eval @ client.js?df86:862
stream.js?553e:64 WebSocket connection to 'wss://mqtt.ably.io:8883/' failed: Connection closed before receiving a handshake response
WebSocketStream @ stream.js?553e:64
createWebSocket @ ws.js?fcb9:59
buildBuilderBrowser @ ws.js?fcb9:85
wrapper @ index.js?e7fc:148
MqttClient._setupStream @ client.js?df86:263
MqttClient._reconnect @ client.js?df86:847
eval @ client.js?df86:862
stream.js?553e:64 WebSocket connection to 'ws://mqtt.ably.io:8883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
WebSocketStream @ stream.js?553e:64
createWebSocket @ ws.js?fcb9:59
buildBuilderBrowser @ ws.js?fcb9:85
wrapper @ index.js?e7fc:148
MqttClient._setupStream @ client.js?df86:263
MqttClient._reconnect @ client.js?df86:847
eval @ client.js?df86:862
首先,URI 应该以正确的模式开头,例如mqtts://
不仅仅是mqtts:
其次,实际上是导致问题的原因,您只能从浏览器中连接到支持websocket或安全websocket的代理。您不能从页面内连接到本机 MQTTS 代理。看起来 Ally 的代理期待端口 8883 上的原生 MQTT,而不是 Websockets 上的 MQTT。
你会得到这个,因为浏览器只支持WebSockets上的MQTT,而不仅仅是原生MQTT。Ably的MQTT代理仅支持本机MQTT,因此这将失败。
但是,可以使用其中一个客户端库或 SSE 通过 WebSocket 连接到 Able。即使数据从您拥有的某些设备使用 MQTT 发布到 Able,Ably 也会在协议之间进行转换,并以您订阅的任何协议分发数据。例如,如果要通过 SSE 订阅数据,则只需使用:
var key ='YOUR_ABLY_API_KEY';
var url ='https://realtime.ably.io/event-stream?channels=myChannel&v=1.2&key=' + key;
var eventSource = new EventSource(url);
eventSource.onmessage = function(event) {
var message = JSON.parse(event.data);
console.log('Message: ' + message.name + ' - ' + message.data);
};
这将为您订阅 Ably 频道,并在onmessage
功能中传递消息。