Preface:

Two years ago, I wrote a websocket heartbeat blog – a preliminary study and implementation of websocket heartbeat reconnection. I’ve been reading a lot and recently considered writing my own NPM package, so I’ve completed a library for detecting websocket heartbeats. Here I would like to thank a few of my friends for their help.

introduce

Websocket-heartbeat -js Is based on the native Websocket encapsulation of browser JS to ensure the connection status between the client websocket and the server. The program has heartbeat detection and automatic reconnection mechanism. When the network is disconnected or the back-end service problems cause the client Websocket to be disconnected, the program will automatically try to reconnect until the connection is successful again.

The principle of

When using native Websocket, if the device network is disconnected, no function is triggered, and the front-end program cannot know that the current connection is disconnected. If the websocket.send method is called, the browser will find that the message cannot be sent and will trigger onclose immediately or after a certain amount of time (depending on the browser or browser version).

The back-end Websocket service may also be abnormal. After the connection is disconnected, the front-end does not receive any notification. Therefore, the front-end needs to send heartbeat ping messages periodically. If no PONG message is received within a certain period of time, it indicates that the connection is abnormal and the front end will perform reconnection.

To solve the preceding two problems, the former end acts as the active party and periodically sends ping messages to check the connection between the network and the front and back ends. Once an exception is found, the front end continues to perform the reconnect logic until the reconnect succeeds.

convention

1. Close the WebSocket connection

If you need to disconnect the websocket, should perform WebsocketHeartbeatJs. Close (), WebsocketHeartbeatJs. Ws is native websocket instance object, WebsocketHeartbeatJs. Ws. Onclose, has been binding reconnection method, if the back-end websocket services directly to close the connection, front-end WebsocketHeartbeatJs. Ws. Onclose can be performed, WebsocketHeartbeatJs will try to reconnect. If the back-end to tell front end need to be disconnected, need to send a particular message to the front, the front-end received a specific message, call WebsocketHeartbeatJs. Close (), WebsocketHeartbeatJs will not reconnection.

websocketHeartbeatJs.onmessage = (e) => {
    if(e.data == 'close') websocketHeartbeatJs.close();
}
Copy the code

2.ping & pong

The front-end sends a ping message, and the back-end needs to return a Pong message as soon as it receives it. The Pong message can be any value. Websocket-heartbeat-js does not process the PONG message, but simply resets the heartbeat when any message is received, because if any message is received, the connection is fine.

usage

The installation

npm install websocket-heartbeat-js

Copy the code

Introduction to use

import WebsocketHeartbeatJs from 'websocket-heartbeat-js';
let websocketHeartbeatJs = new WebsocketHeartbeatJs({
    url: 'ws://xxxxxxx'
});
websocketHeartbeatJs.onopen = function () {
    console.log('connect success');
    websocketHeartbeatJs.send('hello server');
}
websocketHeartbeatJs.onmessage = function (e) {
    console.log(`onmessage: ${e.data}`);
}
websocketHeartbeatJs.onreconnect = function () {
    console.log('reconnecting... ');
}
Copy the code

or

<script src="./node_modules/websocket-heartbeat-js/dist/index.js"></script>
let websocketHeartbeatJs = new window.WebsocketHeartbeatJs({
    url: 'ws://xxxxxxx'
});
Copy the code

API

websocketHeartbeatJs.ws (WebSocket)

Websocket-heartbeat-js simply encapsulates heartbeat related hook functions. Websocketheartbeatjs. ws is a native WebSocket instance. If you need more webSocket features, Please directly operate webSockeTheartBeatjs.ws.

WebsocketHeartbeatJs. Ws is equal to the WebSocket (websocketHeartbeatJs. Opts. Url);Copy the code

websocketHeartbeatJs.opts (Object)

attribute mandatory type The default value describe
url true string none Websocket Server interface address
pingTimeout false number 15000 The heartbeat is sent every 15 seconds and the timer is reset if any back-end messages are received
pongTimeout false number 10000 If the ping message is not received within 10 seconds after being sent, the connection is considered disconnected
reconnectTimeout false number 2000 The interval between retry attempts
pingMsg false string “heartbeat” Ping news value
const options = {
    url: 'ws://xxxx',
    pingTimeout: 15000, 
    pongTimeout: 10000, 
    reconnectTimeout: 2000,
    pingMsg: "heartbeat"
}
let websocketHeartbeatJs = new WebsocketHeartbeatJs(options);
Copy the code

websocketHeartbeatJs.send(msg) (function)

Send messages to the back end

websocketHeartbeatJs.send('hello server');

Copy the code

websocketHeartbeatJs.close() (function)

The front end manually disconnects the Websocket connection. This method does not trigger reconnection. websocketHeartbeatJs.close()

Hook functions and event functions

websocketHeartbeatJs.onclose (function)

websocketHeartbeatJs.onclose = () => {
    console.log('connect close');
}
Copy the code

websocketHeartbeatJs.onerror (function)

websocketHeartbeatJs.onerror = () => {
    console.log('connect onerror');
}
Copy the code

websocketHeartbeatJs.onopen (function)

websocketHeartbeatJs.onopen = () => {
    console.log('open success');
}
Copy the code

websocketHeartbeatJs.onmessage (function)

websocketHeartbeatJs.onmessage = (e) => {
    console.log('msg:', e.data);
}
Copy the code

websocketHeartbeatJs.onreconnect (function)

websocketHeartbeatJs.onreconnect = (e) => {
    console.log('reconnecting... ');
}
Copy the code

demo

demo show

npmjs:https://www.npmjs.com/package/websocket-heartbeat-js

github:https://github.com/zimv/websocket-heartbeat-js



Follow the official account of the great poet, the first time to get the latest articles.