uniapp连接MQTT

一、安装依赖

npm install [email protected]
注意要指定下载3.0.0版本

二、废话少说直接上代码

1. main.js全局注册MQTT

代码如下(示例):

const MQTT = require('mqtt/dist/mqtt.js')
Vue.prototype.$MQTT = MQTT;  //挂载在 Vue 实例上

2. 调用

我用的nvue,而且没有全局需求,并没有把MQTT连接注册到全局,根据自身需求,以下仅为示例

代码如下(示例):

// 引入MQTT
const MQTT = require('mqtt/dist/mqtt.js')
// 声明client
data(){
    
    
	return {
    
    
		client: null
	}
}
// 连接方法
methods: {
    
    
	MQTTINIT(){
    
    
		let options = {
    
    
			username: '',
			clientId: '',
			connectTimeout: 600000,
			keepalive: 5, // 心跳,单位秒,如果后台开启监听可以快速知道有没有退出
			clean: true,
			// password: '',
      		// reconnectPeriod: 5000,
		}
		// 订阅 topic。如果订阅多个 var subscribe = ["test1","test2"]
		var subscribe = "test"
		
		if(this.client){
    
     
			this.client.end()
		}
		// #ifdef APP-PLUS
			this.client = MQTT.connect('wx://xxxxxxxxxxx:xxxx/mqtt',options)  
		// #endif
		// #ifdef H5
			this.client = MQTT.connect('ws://xxxxxxxxxxx:xxxx/mqtt',options)  
		// #endif
		this.client.on('connect', (res)=>{
    
      
			console.log(res,1111);
			uni.hideLoading()
			uni.showToast({
    
      
				title:"连接成功",  
				duration:2000,  
				icon:"none"  
			})
			this.client.subscribe(subscribe , (err)=>{
    
      
				console.log(err,2222);
				if (!err) {
    
      
					uni.showToast({
    
      
						title:"订阅成功",  
						duration:2000,  
						icon:"none"  
					})  
				}  
			})  
		}).on('message', (topic, message)=>{
    
      
			console.log(topic,message)  
		}).on('reconnect', (topic, message)=>{
    
      
			uni.showLoading({
    
    
				title: '重连中...'
			})
			console.log("重连")  
		}).on('error',()=>{
    
    
			//重新连接
			client.reconnect()
		})
		// close: function () {} 断开连接回调
		// offline : function () {} 客户端离线回调
		// 发送,
		// this.client.publish('system','hello',{},(res)=>{
    
    
		// 		console.log(res)
		// })
		//  system: topic订阅的主题,第二个参数发送内容Buffer or String类型(可以转成JSON字符串JSON.stringify()),第三个参数[options]看下方【不必填】,第四个回调【不必填】
		// 	qos QoS 等级, Number, default 0
		//	retain 保留消息标志, Boolean, default false
		//	dup 重复标志, Boolean, default false
		
	}
}

工具可以作为测试使用,模拟后台收发逻辑,不需要可跳过

三、MQTT调试工具 下载地址

一、修改工具语言,切换为中文,默认英文

在这里插入图片描述

二、新建连接

在这里插入图片描述

三、只需填写名称(随便写),地址(后台提供),(端口号应该默认的不用动)。然后点击右上角连接

在这里插入图片描述

四、添加订阅,即uniapp创建连接后添加的订阅,填写完后点击确定

在这里插入图片描述

五、发送测试消息

在这里插入图片描述

六、正常接收消息

在这里插入图片描述


原创不易,转载请注明出处!!!如果本文对你有所帮助,给个点赞、收藏再走呗。

猜你喜欢

转载自blog.csdn.net/qq_44860866/article/details/129714553