uniapp 使用mqtt 报错 socketTask onOpen is not a function

1. 报错的解决方法

在man.js文件添加这个

// #ifndef MP
// 处理 wx.connectSocket promisify 兼容问题,强制返回 SocketTask
uni.connectSocket = (function(connectSocket) {
	return function(options) {
		console.log(options)
		options.success = options.success || function() {}
		return connectSocket.call(this, options)
	}
})(uni.connectSocket)
// #endif

1. 安装mqtt,使用[email protected]

yarn add [email protected]

或 
npm install [email protected]

为啥不用最新版本4.0,主要是最新版有问题,根据用不起。

2. 建立连接,监听消息

let options = {
		clientId: "web-" + Math.random().toString(36).replace('.', ''),
		protocolVersion: 5,
		keepalive: 30,
		connectTimeout: 5 * 1000,
}

let url = "wx://127.0.0.1:8088/mqtt";
let client = mqtt(url,options); //1.发起连接

client.on("connect", () => {    //2. 监听连接是否成功
	 console.log('连接成功');  
	 client.subscribe("user/11", (err) => { });   //3.订阅用户频道
});

你可能感兴趣的:(uniapp,uniapp)