uniapp uses mqtt and reports an error socketTask onOpen is not a function

1. Solutions to error reports

Add this to the man.js file

// #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. Install mqtt and use [email protected]

yarn add [email protected]

或 
npm install [email protected]

Why don't you use the latest version 4.0? The main reason is that the latest version has problems and you can't afford it.

2. Establish a connection and listen for messages

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.订阅用户频道
});

Guess you like

Origin blog.csdn.net/tengyuxin/article/details/132606767