简体   繁体   中英

Connect to MQTT Broker With Device and Browser

I can create an MQTT broker. I can create a web client also. but there is a problem with the device. I try to connect with the IP(ws://192.168.1.240:1883) of the device. The device could not connect to the broker. Web client could connect with WebSocket.

const aedes = require('aedes')()
const httpServer = require('http').createServer()
const ws = require('websocket-stream')
const port = 1883

ws.createServer({ server: httpServer }, aedes.handle)

httpServer.listen(port, function () {
  console.log('websocket server listening on port ', port)
});

I try to use another way to create an MQTT broker and it runs. code is below. this time device connected to the broker. But the Web browser could not connect to the broker. The browser wants to connect ws://192.168.1.240:1883 . So the browser wants WebSocket .

const aedes = require('aedes')()
var server = require('net').createServer(aedes.handle);
var cors = require('cors');

const ip = "192.168.1.240";
const port = 1883;

const httpServer = require('http').createServer();
const io = require('socket.io')(httpServer, {
  cors: {
    origin: "*",
    credentials: true
  }
});

httpServer.listen(8091, () => {
  console.log("Http Server and Socket.io are Running !");
});

server.listen(port, ip, () => {
  console.log("TCP Server is Running !")
});

How can I create connectable a broker or server for devices and browsers?

Thanks

If you want to use both MQTT over Websockets and native MQTT you will need to configure the broker to listen on 2 separate ports. You can't listen for both on the same port.

eg This will accept native MQTT connections on 1883 and Websocket connections on 8883

const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
const httpServer = require('http').createServer()
const ws = require('websocket-stream')
const port = 1883
const wsPort = 8883 

server.listen(port, function () {
  console.log('server started and listening on port ', port)
})

ws.createServer({ server: httpServer }, aedes.handle)

httpServer.listen(wsPort, function () {
  console.log('websocket server listening on port ', wsPort)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM