search
HomeWeChat AppletMini Program DevelopmentNative 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 = &#39;&#39;;

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(&#39;../../config/socket.js&#39;);
const app = getApp();
data: {
  motto: &#39;Hello World&#39;,
  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

Detailed explanation of the problem of disconnection and reconnection of Spring boot database connection in java

Json object and String conversion, json data splicing and detailed introduction to JSON usage (summary)

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools