emqx / MQTT-Client-Examples

MQTT Client Examples
https://www.emqx.com
MIT License
843 stars 680 forks source link

Web socket error: Connection closed before receiving a handshake response #29

Open lubeHub opened 3 years ago

lubeHub commented 3 years ago

When I run on 127.0.0.1:8000 your test example it works well. But when I am trying to connect to ThingSpeak it give me error: WebSocket connection to 'ws://mqtt3.thingspeak.com:1883/' failed: Connection closed before receiving a handshake response

Here is ThingSpeaks documentation how to connect: https://www.mathworks.com/help/thingspeak/subscribetoachannelfeed.html Here is my info: connection: { host: 'mqtt3.thingspeak.com', port: 1883, endpoint: '/mqtt', clean: true, // Reserved session connectTimeout: 4000, // Time out reconnectPeriod: 4000, // Reconnection interval // Certification Information clientId: 'myId', username: 'myUsername', password: 'myPassword', },

Here is my Connect code: createConnection() { // 连接字符串, 通过协议指定使用的连接方式 // ws 未加密 WebSocket 连接 // wss 加密 WebSocket 连接 // mqtt 未加密 TCP 连接 // mqtts 加密 TCP 连接 // wxs 微信小程序连接 // alis 支付宝小程序连接 const { host, port, endpoint, ...options } = this.connection const connectUrl =mqtt://${host}:${port}${endpoint} try { this.client = mqtt.connect(connectUrl, options) } catch (error) { console.log('mqtt.connect error', error) } this.client.on('connect', () => { console.log('Connection succeeded!') }) this.client.on('error', error => { console.log('Connection failed', error) }) this.client.on('message', (topic, message) => { this.receiveNews = this.receiveNews.concat(message) console.log(Received message ${message} from topic ${topic}) }) },

I tried changing in connectUrl mqtt and ws and mqtts and ws but does not work. I also tried removingendpointand addingtopicasendpoint` because there is no endpoint in ThingsSpeak documentation but still nothing.

lubeHub commented 3 years ago

I mannaged to connect using websocket and port: 80

zibuyu1995 commented 3 years ago

If you need to connect to a Websocket, then your address should be ws://mqtt3.thingspeak.com:80