vue中使用mqtt

755 阅读2分钟

1.安装包

npm i mqtt --save

mqtt这个是需要在node中运行的,在vue中使用,可能会报错# Vue Uncaught ReferenceError: process is not defined 所以,需要修改下配置 我使用的是webpack,我的配置是

const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack');
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        Buffer: ['buffer', 'Buffer'],
      }),
      new webpack.ProvidePlugin({
        process: 'process/browser',
      }),
    ],
  }

})

以上是我的vue.config.js的配置

当然,如果你使用的是vite,那么网上有很多例子解决你的问题

2.建立客户端连接后订阅主题

const host = 'yourhost'
const port = '23456'
let connectUrl = `mqtt://${host}:${port}`

client = mqtt.connect(connectUrl,{
  clientId: `mqtt_${Math.random().toString(16).slice(3)}`,
  clean: true,
  connectTimeout: 4000,
  username: 'xxx',
  password: 'xxx',
  protocolVersion: 3,//这个是版本限制,如果不需要可以删掉
  reconnectPeriod: 1000,
})
client.on('connect', () => {
  console.log("连接成功:");
  const topic = 'test/info'
  client.subscribe([topic], () => {
    console.log(`Subscribe to topic: '${topic}'`)
  })
});
client.on('error', (error) => {
  console.log(error);
});
client.on('message', (topic, payload) => {
  //--控制命令
  var info = payload.toString()
  console.log(info);

})

好了,结束。

因为浏览器中是不能使用mqtt的,所以,他这个连接其实是websocket的连接,你可以打印一下你的client你就可以看到。所以,这就要保证,这里使用的端口必须是服务器上mqtt中对应的ws的端口才可以,这一点很重要。

在mqttserver.js服务端代码中,你需要这样配置

var mqttServ = new mosca.Server({
  http: {
    port: 23456,//   协议头 ws://
  },
  port: 1883,//     协议头 mqtt://
});

这个http里面的这个端口就是ws://xxx.com/:23456 ,你的浏览器中需要用这个地址,不能使用mqtt://xxx.com/:1883, 经过测试,你完全可以在别的地方使用mqtt://xxx.com/:1883 建立客户端,他发送的消息ws://xxx.com/:23456 也是可以收到的。

附一个参考链接:www.emqx.com/zh/blog/how…

附我的服务端代码:

var mosca = require('mosca');
var authenticate = function(client, username, password, callback) {
        console.log(username,password)
    var authorized = (username === 'xxx' && password.toString() === 'xxx');
    if (authorized) client.user = username;
    callback(null, authorized);
 }
// 授权为alice的客户端可以发布/users/alice,
// 从主题中取得用户名,并校验与授权用户一致
var authorizePublish = function(client, topic, payload, callback) {
  callback(null, payload);
}

// 授权为alice的客户端可以订阅/users/alice,
// 从主题中取得用户名,并校验与授权用户一致
var authorizeSubscribe = function(client, topic, callback) {
  callback(null, topic);
}


var MqttServer = new mosca.Server({
        port: 1883,
        http:{
                port: 23456,
        }

});

MqttServer.on('clientConnected', function (client) {
    console.log('client connected:', client.id);
    //console.log('client ip:', client.ip);
    console.log('client port:', client.server.opts.port);
        console.log('client name:',client);
    //console.log('client', client);
});

/**********************当服务开启时 *****************************/

MqttServer.on('ready', function (){

   MqttServer.authenticate = authenticate;
   MqttServer.authorizePublish = authorizePublish;
   MqttServer.authorizeSubscribe = authorizeSubscribe;
   console.log('Mosca server is up and running')

    console.log('mqtt is running...');
});