<> preface :

Recently, I want to uni-app Used in applet websocket Dual communication , and uni-app In the plug-in Market websocket Also made a good package , for example :socket.io, However, due to the use of backend java of websocket, Cause I'm socket of url It always doesn't correspond to that side , So we can only change it into original websocket, and uni-app in websocket Many articles are introduced , However, direct use always has more or less problems , Therefore, it is encapsulated and modified , And it can be used normally in the project , Here's the code

<> encapsulation websocket
class websocketUtil { constructor(url, time) { this.is_open_socket = false
// Avoid duplicate connections this.url = url // address this.data = null // Heartbeat detection this.timeout= time
// How many seconds does the test take this.heartbeatInterval= null // Check whether the server side is still alive this.reconnectTimeOut= null
// How long after reconnection try { return this.connectSocketInit() } catch (e) { console.log(
'catch'); this.is_open_socket = false this.reconnect(); } } //
Create when entering this page websocket connect 【 The entire page is ready to use 】 connectSocketInit() { this.socketTask = uni.
connectSocket({ url: this.url, success:()=>{ console.log(" Preparing to establish websocket in ...");
// Return instance return this.socketTask }, }); this.socketTask.onOpen((res) => { console.
log("WebSocket Normal connection !"); clearTimeout(this.reconnectTimeOut) clearTimeout(this.
heartbeatInterval) this.is_open_socket = true; this.start(); // notes : Only the connection is normally open
, To receive the message normally this.socketTask.onMessage((res) => { console.log(res.data) }); }) //
Listening connection failed , The reason why I commented out the code here is because if the server is shut down , And below onclose Method , This will cause duplicate connections //
uni.onSocketError((res) => { // console.log('WebSocket Connection open failed , Please check !'); //
this.is_open_socket = false; // this.reconnect(); // }); //
This is only event monitoring 【 If socket If it is closed, it will be executed 】 this.socketTask.onClose(() => { console.log(" It has been closed ")
this.is_open_socket = false; this.reconnect(); }) } // send message send(value){ //
notes : Only the connection is normally open , To send messages normally and successfully this.socketTask.send({ data: value, async success() {
console.log(" Message sent successfully "); }, }); } // Turn on heartbeat detection start(){ this.heartbeatInterval =
setTimeout(()=>{ this.data={value:" Transmission content ",method:" Method name "} console.log(this.data)
this.send(JSON.stringify(this.data)); },this.timeout) } // Reconnect reconnect(){
// Stop sending heartbeat clearInterval(this.heartbeatInterval) // If it wasn't shut down artificially , Reconnection if(!this.
is_open_socket){ this.reconnectTimeOut = setTimeout(()=>{ this.connectSocketInit
(); },3000) } } } module.exports = websocketUtil
<> Call mode

<>1. Single page call

* introduce import wsRequest from './static/js/websocket.js'
* use new wsRequest("ws://xxx:3100/connect/websocket",5000)
<>2. Global call

* stay main.vue On page // introduce websocket file import wsRequest from
'./static/js/websocket.js' // open websocket let websocket = new wsRequest(
"ws://xxx:3100/connect/websocket",5000) // Mount to global Vue.prototype.$socket =
websocket
* Middle note let data={value:" Transmission content ",method:" Method name "} this.$socket.send(JSON.stringify
(data));
<> matters needing attention
// When testing the environment url Can be written as ws://xxx:3100/connect/websocket new wsRequest(
"ws://xxx:3100/connect/websocket",5000) // Release experience version or official version ,url Be sure to write
wss://xxx:3100/connect/websocket new wsRequest(
"wss://xxx:3100/connect/websocket",5000)
besides , We also need to develop small programs in wechat management platform –> Development management –> Development settings –> Server domain name Add the following configuration

Technology