websocket heartbeat mechanism

WebSocket is a technology that creates a persistent connection between a client and a server. In order to maintain the stability of the connection, it is necessary to maintain the WebSocket connection by sending heartbeat messages.

1. Create a basic use of websocket

// 创建 WebSocket 对象,传入服务器地址
const socket = new WebSocket('ws://url');

// 监听 WebSocket 的打开事件
socket.addEventListener('open', (event) => {
  // 在此处理连接打开时的逻辑
});

// 监听 WebSocket 接收到消息的事件
socket.addEventListener('message', (event) => {
  // 在此处理从服务器接收到的消息的逻辑
});

// 监听 WebSocket 关闭事件
socket.addEventListener('close', (event) => {
  // 在此处理连接关闭时的逻辑
});

// 监听 WebSocket 发生错误的事件
socket.addEventListener('error', (event) => {
  // 在此处理连接发生错误时的逻辑
});

// 向服务器发送消息
socket.send('Hello, server!');

2. After the client connects to the WebSocket server, the heartbeat message is sent regularly through the setInterval method

let ws = new WebSocket('ws://localhost:8080');
let heartCheck;

ws.onopen = function() {
  heartCheck = setInterval(function() {
    ws.send('HeartBeat');
  }, 5000);  // 发送心跳消息的时间间隔,单位毫秒
}

The code here will send a heartbeat message to the server every 5 seconds

3. When the client receives the message sent by the server, clear the heartbeat timer. Because if the server keeps pushing messages, there is no need to send heartbeat messages

let ws = new WebSocket('ws://url');
let heartCheck;

ws.onopen = function() {
  heartCheck = setInterval(function() {
    ws.send('HeartBeat');
  }, 5000);
}

ws.onmessage = function() {
  clearInterval(heartCheck);
  heartCheck = setInterval(function() {
    ws.send('HeartBeat');
  }, 5000);
}

When the client receives the message sent by the server, the original heartbeat timer is cleared and a heartbeat timer is recreated to ensure the connection status of the WebSocket.

4. When the client detects that the WebSocket connection is closed, clear the heartbeat timer. Because if the WebSocket connection is closed, the heartbeat timer is meaningless

let ws = new WebSocket('ws://url');
let heartCheck;

ws.onopen = function() {
  heartCheck = setInterval(function() {
    ws.send('HeartBeat');
  }, 5000);
}

ws.onmessage = function() {
  clearInterval(heartCheck);
  heartCheck = setInterval(function() {
    ws.send('HeartBeat');
  }, 5000);
}

ws.onclose = function() {
  clearInterval(heartCheck);
}

The heartbeat timer is cleared when a closed WebSocket connection is detected

Guess you like

Origin blog.csdn.net/weixin_48329823/article/details/130250309