解决微信小程序MQTT通讯真机调试失败的问题附加可用代码

原因:模拟器上测试可以,选中了不校验合法域名,真机调试没能连接服务器,解决思路换了个mqtt.js
可参考

https://unpkg.com/[email protected]/dist/mqtt.min.js

废话不多说!上代码
前端部分自己改改就可以用了,我懒得改了
微信小程序index.wxml

<view style="width: 750rpx;height:330rpx;">  
<image src="https://img-blog.csdnimg.cn/295062b06acc4f94b73cae854ee15d5f.png" style="width: 750rpx;height:330rpx;"></image>
</view>

<view style="width: 750rpx;height:800rpx;display: flex;flex-direction: column;justify-content: center;justify-items: center;background-color: royalblue;">
 
<!-- 开关 -->
<view style="background-color: salmon;width: 750rpx;height: 400rpx;display: flex;flex-direction: row;padding-top: 10rpx;">
<button type="warn" style="width: 180rpx;height: 80rpx;" bindtap="public" data-id="1">打开</button>
<button type="warn" style="width: 180rpx;height: 80rpx;" bindtap="public" data-id="0">关闭</button>
</view>
<!-- 状态 -->
<view style="background-color: rgb(216, 184, 181);width: 750rpx;height: 400rpx;display: flex;flex-direction: column;font-size: larger;color: seashell;font-weight: 1000;">
<text>状态:{
    
    {
    
    state}}</text>
<text>位置:</text>
</view>
</view>

index.js

// index.js
import mqtt from '../../utils/mqtt.js'    //引入mqtt
// import mqtt from '../../utils/mqtt.js';
let client = null;
// 获取应用实例
const app = getApp()

Page({
    
    
	data: {
    
    
		state:'未连接..' 
  },

	
public:function(ee){
    
    
//消息发送
	console.log(ee.currentTarget.dataset.id);
// 发布消息
client.publish('pop', ee.currentTarget.dataset.id);

wx.showToast({
    
    
	title: '请求成功',
	icon:'none'
})
},
connectMqtt: function() {
    
    
		
		var clinet_id = parseInt(Math.random() * 100 + 888888888, 10);
		console.log('wx_' + clinet_id);
		const options = {
    
    
				connectTimeout: 4000, // 超时时间
				clientId: 'wx_' + clinet_id,
				username: '账号',
				password: '密码',
		}

		client = mqtt.connect('wx://你的ip:8083/mqtt', options)
		console.log(client);
		client.on('reconnect', (error) => {
    
    
				console.log('正在重连:', error)
		})

		client.on('error', (error) => {
    
    
				console.log('连接失败:', error)
		})

		let that = this;
		client.on('connect', (e) => {
    
    
				console.log('成功连接服务器')
       //订阅一个主题
				client.subscribe('pop', {
    
    
						qos: 0
				}, function(err) {
    
    
						if (!err) {
    
    
								console.log("订阅成功")
								that.setData({
    
    
									state:'已连接pop服务器'
								})
							
						}
				})
		})
		
		client.on('message', function (topic, message) {
    
    
				console.log('received msg:' + message.toString());
				// wx.showToast({
    
    
				// 	title: message.toString(),
				// })
		})
},

onLoad:function(){
    
    
	let that=this;
	that.connectMqtt();
	
},

		
})

无法在真机上使用的请换一下MQTT的js

猜你喜欢

转载自blog.csdn.net/qq_35230125/article/details/124911845