nodejs版mqtt

1.mqtt server

  其中3001为mqtt的websockets端口,3003为tcp端口,3004为wss端口(需要后续通过nginx代理ssl转发)。

const mosca = require('mosca');

const wsPort = 3001;
const tcpPort = 3003;
const MqttWsServer = new mosca.Server({
    port:tcpPort,
    http: {
        port: wsPort,
        bundle: true,
        static: './'
    }
});

// 监听连接
MqttWsServer.on("clientConnected", (client)=> console.log("connecting clientId:",client.id));
MqttWsServer.on('ready',() => console.log("mqtt is running at ws://localhost:%s,tcp://localhost:%s,wss://localhost:3004", wsPort,tcpPort));
MqttWsServer.on("published", (packet,client) => {
    if(client){
        console.log('ws:'+client.id + '发布主题:' + packet.topic + ',内容:' + packet.payload.toString());
    }
});

2.ws客户端代码

const mqtt = require('mqtt');

const clientId = 'mqttws_' + Math.random().toString(16).substr(2, 8)
const host = 'ws://192.6.1.74:3001'
var options = {
    keepalive: 60,
    clientId: clientId,
    protocolId: 'MQTT',
    protocolVersion: 4,
    clean: true,
    reconnectPeriod: 1000,
    connectTimeout: 30 * 1000,
    will: {
        topic: 'WillMsg',
        payload: 'Connection Closed abnormally..!',
        qos: 0,
        retain: false
    },
    username: 'ws',
    password: 'ws',
    rejectUnauthorized: false
}

var client = mqtt.connect(host, options)

client.on('error', function (err) {
    console.log(err)
    client.end()
})

client.on('connect', function () {
    console.log('client connected:' + clientId)
})

client.subscribe('topic', { qos: 0 })

client.publish('topic', 'ws connection demo...!', { qos: 0, retain: false })

client.on('message', function (topic, message, packet) {
    console.log('Received Message:' + message.toString() + '\nOn topic:= ' + topic)
})

client.on('close', function () {
    console.log(clientId + ' disconnected')
})

3.nginx代理转发ws的ssl

	upstream mqttws  {
		server 192.6.1.74:3001;
	}

    server {
        listen       3004 ssl;
        server_name  localhost;
        ssl on;
        ssl_certificate      C:\\frotech\\scratch-desktop-bak\\nginx-1.14.0\\ssl\\mqtt18501.crt;
        ssl_certificate_key  C:\\frotech\\scratch-desktop-bak\\nginx-1.14.0\\ssl\\mqtt18501.key;
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;
		
        location /mqtt {
            proxy_pass http://mqttws;
			proxy_set_header   Host             $host;
			proxy_set_header   X-Real-IP        $remote_addr;
			proxy_set_header   X-Forwarded-For  $remote_addr;
			
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }

4.wss客户端代码

const mqtt = require('mqtt');

const clientId = 'mqttws_' + Math.random().toString(16).substr(2, 8)
const host = 'wss://192.6.1.74:3004/mqtt'
var options = {
    keepalive: 60,
    clientId: clientId,
    protocolId: 'MQTT',
    protocolVersion: 4,
    clean: true,
    reconnectPeriod: 1000,
    connectTimeout: 30 * 1000,
    will: {
        topic: 'WillMsg',
        payload: 'Connection Closed abnormally..!',
        qos: 0,
        retain: false
    },
    username: 'ws',
    password: 'ws',
    rejectUnauthorized: false
}

var client = mqtt.connect(host, options)

client.on('error', function (err) {
    console.log(err)
    client.end()
})

client.on('connect', function () {
    console.log('client connected:' + clientId)
})

client.subscribe('topic', { qos: 0 })

client.publish('topic', 'wss connection demo...!', { qos: 0, retain: false })

client.on('message', function (topic, message, packet) {
    console.log('Received Message:' + message.toString() + '\nOn topic:= ' + topic)
})

client.on('close', function () {
    console.log(clientId + ' disconnected')
})

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kenick

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值