Home > Article > WeChat Applet > Native WebSokcet implementation method for disconnection reconnection and data splicing
WebSocket protocol is a new protocol of HTML5. It implements full-duplex communication between the browser and the server. This article mainly shares with you the WeChat applet using native WebSokcet to realize disconnection reconnection and data splicing. I hope it can help everyone.
1. Description
1. The native WebSokcet of the mini program does not have a disconnection and reconnection mechanism. This is its shortcoming.
2. The new version library of the mini program already supports multiple WebSokcet connections.
Official description: Before Basic Library 1.7.0, a WeChat applet could only have one WebSocket connection at the same time. If a WebSocket connection currently exists, the connection will be automatically closed and a new WebSocket connection will be created. Basic library version 1.7.0 and later supports multiple WebSokcet connections, and each successful call to wx.connectSocket will return a new SocketTask.
Official document address: https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html#wxclosesocket
2. Practical examples:
First you need the socket address url: let url = 'wss://http://xxx.xxx.com/?xxx=xxx'
Note: 1. Add the socket in the mini program management background The port cannot appear in the domain name; 2. If appID is used, the protocol must be wss; 3. The port mapped by the socket server only supports 80 and 443, which is the same as the official account.
Next examples:
1, socket.js
const app = getApp(); let url = 'wss://xxx.xxx.com/?xxx=xxx' export const connect = function (cb) { // 定义一个方法 wx.connectSocket({ // 创建一个 WebSocket 连接 url: url, fail (err) { if (err) { console.log('%cWebSocket连接失败', 'color:red', err) app.globalData.socketConnectFail = true // 定义一个全局变量,当链接失败时改变变量的值 } } }) wx.onSocketOpen(function (res) { // 监听WebSocket连接打开事件。 console.log('WebSocket打开成功'); wx.sendSocketMessage({ // 通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。 data: String2Base64(), // 用于订阅的参数,视具体情况而定 success (data) { console.log('WebSocket发送消息:', data.errMsg) }, fail (err) { console.log('Err', err) } }) }) wx.onSocketMessage(function (res) { // 监听WebSocket接受到服务器的消息事件。 console.log('WebSocket接收到消息:', ArryBuffer2Json(res.data)); cb(ArryBuffer2Json(res.data)); // 将接收到的消息进行回调,如果是ArryBuffer,需要进行转换 }) wx.onSocketError(function (res) { // 监听WebSocket错误。 console.log('WebSocket连接打开失败') }) wx.onSocketClose(function (res) { // 监听WebSocket关闭。 console.log('WebSocket关闭'); }) }; function ArryBuffer2Json (data) { // ArryBuffer转换成Json try { var encodedString = String.fromCharCode.apply(null, new Uint8Array(data)); var decodedString = decodeURIComponent(atob(encodedString)); return JSON.parse(decodedString); } catch (err) { console.log(err); return false; } } function String2Base64 () { // 用于订阅的参数,视具体情况而定 var packet = {}; packet["cmd"] = "subscribe"; packet["reqNo"] = "" + new Date().getTime(); packet["params"] = {token: token, channelId: 'xcx', columnIds: "1"}; return stringToUint(JSON.stringify(packet)) } function stringToUint (string) { var string = base64_encode(encodeURIComponent(string)), charList = string.split(''), uintArray = []; for (var i = 0; i < charList.length; i++) { uintArray.push(charList[i].charCodeAt(0)); } return new Uint8Array(uintArray); } function base64_encode (str) { // base64转码 var c1, c2, c3; var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var i = 0, len = str.length, string = ''; while (i < len) { c1 = str.charCodeAt(i++) & 0xff; if (i == len) { string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt((c1 & 0x3) << 4); string += "=="; break; } c2 = str.charCodeAt(i++); if (i == len) { string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)); string += base64EncodeChars.charAt((c2 & 0xF) << 2); string += "="; break; } c3 = str.charCodeAt(i++); string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)); string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)); string += base64EncodeChars.charAt(c3 & 0x3F) } return string }
2, index.js
let openSocket = require('../../config/socket.js'); const app = getApp(); data: { motto: 'Hello World', articleData: [] }, onLoad: function () { let that = this; openSocket.connect(function (data) { // WebSocket初始化连接 let result = data.data if (result) { that.setData({articleData: [result].concat(that.data.articleData)}) // 将获得的socket推送消息拼接到当前文章列表的最前面 } }); if (app.globalData.socketConnectFail) { // WebSocket断线重连 setInterval(() => { openSocket.connect(function (data) { let result = data.data if (result) { that.setData({articleData: [result].concat(that.data.articleData)}) } }); }, 1000) } }
3、app.js globalData: { socketConnectFail: false}
Related recommendations:
Recommended articles about disconnection and reconnection
The above is the detailed content of Native WebSokcet implementation method for disconnection reconnection and data splicing. For more information, please follow other related articles on the PHP Chinese website!