vue项目使用mqtt通信

需要使用mqtt订阅通信,我按网上教程,一直连不上,后端给的地址是tcp开头的

img


```javascript

//后端给的



"mqtt": {
"address": "tcp://10.11.44.171:1883",
"clientId": "web",
"user": "web",
"password": "1234567",
}
// 主题为:/cloud_171/ServiceStatus

// 前端目前代码

你就按照后端给的参数进行连接,tcp开头的是可以连上的


        //Mqtt连接方法
        mqttConnection() {
            this.client = mqtt.connect(this.mqttIp, {
                username: this.connectInfo.userName,
                password: this.connectInfo.password
            });
            this.client.on("connect", e =>{
                console.log("连接成功");
                this.client.subscribe(this.topics, (err) => {
                    if (!err) {
                        console.log("订阅成功:" + this.topics);
                    }
                });
            });
            const that = this;
        },

调用:

        const ip = 'ws://10.11.44.171:1883';
        this.mqttIp = ip;
        this.connectInfo =  ...; //自定义
        this.topics = ...; //自定义
        this.mqttConnection();
  1. 小程序还是web建连接?
  2. 我这边可以提供 node 服务做测试,前端用mqttjs@3.0.0版本,其他版本我测试在小程序上会失败
    node部分
//这是node简单服务
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());
    }
});

前端部分(client)

var mqtt = require('mqtt');  
var client2 = mqtt.connect("mqtt://127.0.0.1:1883");   //指定服务端地址和端口
  
client2.subscribe('test',{qos:1});//订阅主题为test的消息  
  
client2.on('message',function(top,message) {  
    console.log(message.toString());  
});  

publish 部分,可以用这一块做推送,这样便于调试

const mqtt = require('mqtt');
 
const clientId = 'mqttws_' + Math.random().toString(16).substr(2, 8)
const host = 'ws://localhost: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')
})

后续mqtt如果做跨平台兼容的话,自己有简单demo也是便于调试的