SoFunction
Updated on 2025-04-07

Mini Program websocket heartbeat library (websocket-heartbeat-miniprogram)

Preface

In 2016, I came into contact with websocket because of the project, and then summarized the heartbeat reconnection and wrote a blog. In 2018, I redeveloped and opened sourced the demo code on github, and finally encapsulated it into a library. as follows:

github: /zimv/websocket-heartbeat-js
npm: /package/websocket-heartbeat-js

In 2020, the beginning of this year, my colleague suggested that you consider compatible with the mini program, and I thought it was pretty good. This time, we have today's websocket-heartbeat-miniprogram. This time, we created a new project based on the previous code and only made the version of the mini program. Because it involves compatibility with various mini programs and related frameworks, we think it is better to release a package separately and focus more on it.

introduce

websocket-heartbeat-miniprogram is encapsulated based on the websocket-related API of the applet, and its main purpose is to ensure the connection status of the client websocket and the server. This program has a heartbeat detection and automatic reconnection mechanism. When the network is disconnected or the backend service problem causes the client websocket to be disconnected, the program will automatically try to reconnect until the connection is successful again. Compatible with most mini programs on the market, WeChat, Baidu, Alipay, etc., as long as they are all unified mini programs wewoscket-API specifications. It also supports mini program frameworks such as Taro. In any case, the business requires a heartbeat mechanism, otherwise in some cases, the connection will be lost and the function will not be used.

usage

Install

npm install --save websocket-heartbeat-miniprogram

Introduce and use

import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram';
WebsocketHeartbeat({
  miniprogram: wx,
  connectSocketParams: {
    url: 'ws://xxx'
  }
})
  .then(task => {
     = () => {//Hook function      ('open');
    };
     = () => {//Hook function      ('close');
    };
     = e => {//Hook function      ('onError:', e);
    };
     = data => {//Hook function      ('onMessage', data);
    };
     = () => {//Hook function      ('reconnect...');
    };
    (data => {//Native instance registration function, lost after reconnection      ('socketTask open');
    });
    (data => {//Native instance registration function, lost after reconnection      ('socketTask data');
    });
  })

This program always uses the applet connectSocket method to connect sockets. If the socket is disconnected, the applet's connectSocket method will be executed again to re-establish the connection. Reconnecting will create a new applet socket instance.

The WebsocketHeartbeat method returns a promise. The returned task object is an instance of this program, providing hook functions such as onOpen, onClose, onError, onMessage, onReconnect, etc. It also exposes the instance of the applet itself (socketTask), which is the instance returned by the applet connectSocket, but the native instance of the applet. They pass the function through the onXXX method for listening and registration. After the socket is reconnected, a new instance is created through the connectSocket internally, and a new applet native instance will be returned. Therefore, these functions that have been registered before will be lost. The hook function provided in this program is still valid after reconnecting. In most cases, it is recommended to use the hook function of this program.

Differences in Alipay mini program

The Alipay applet only allows one socket connection at the same time, and the native API is also slightly different from other applets. This program is already compatible, but it is still important to note that Alipay only allows one socket to be established. If multiple sockets are established, the previous socket will be closed by the system. You must close the old socket through this program instance, otherwise the program will continue to reconnect, resulting in conflicts and unavailability of all sockets.

Agree

1. The socket connection can only be closed actively through the front end

If you need to disconnect the socket, the() method should be executed. If the backend wants to close the socket, it should send a message, the frontend judges the message, and the frontend calls the () method to close it. Because whether the backend calls close or socket close due to other reasons, the frontend socket will trigger the onClose event, and the program cannot determine what causes the closing. Therefore, this program will try to reconnect by default.

import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram';
WebsocketHeartbeat({
  miniprogram: wx,
  connectSocketParams: {
    url: 'ws://xxxx'
  }
})
  .then(task => {
     = data => {
      if( == 'close') ();//Close the socket and no longer reconnect    };
  })

2. Feedback from the backend to the front end heartbeat

The front-end sends a heartbeat message. After the back-end receives it, it needs to return the response message immediately. The message responding to the back-end can be any value, because this program does not process and judge the responding heartbeat message, but only resets the heartbeat after receiving any message, because receiving any message means that the connection is normal. Therefore, when this program receives any message returned by the backend, the heartbeat countdown will be reset to reduce unnecessary requests and reduce server pressure.

API

For details, please refer to:/zimv/websocket-heartbeat-miniprogram

Conclusion

The program has been unit tested, and is also tested in Baidu, Alipay, WeChat and other mini programs and is based on Taro. The program is maintained for a long time, and if you find compatibility problems or program problems, you hope to get issue feedback!

This is the article about the mini program websocket heartbeat library (websocket-heartbeat-miniprogram). For more related mini program websocket heartbeat library content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!