The method of instant messaging and the specific use of webSocket

foreword

I have encountered a scene that requires instant messaging before. At the beginning, I used the polling method, and the timer requested data from the server once every 3 seconds. Later, I found that if the page using this function is opened on the mobile phone for a long time, the mobile phone may fail. Fever, even stuttering. Finally, use webSocket to realize full-duplex communication, allowing the server to actively send requests to the client.

Next, let me introduce the implementation method of instant messaging?

  1. Polling:

    • How it works: The client periodically sends a request to the server to ask if new data is available. If the server has new data, return the data; if not, the server returns an empty response. The client sends the request again immediately after receiving the response, forming a periodic polling process.
    • Advantages: Simple to implement, supported by most browsers and servers.
    • Disadvantages: Frequent requests and responses will cause unnecessary network overhead, reducing performance and efficiency.
    • Applicable scenarios: Applicable to scenarios where data update frequency is not high and real-time requirements are not high.
  2. Long polling (Long Polling):

    • Working principle: The client sends a request to the server, and the server does not return a response immediately, but suspends the request and waits for new data before returning a response. Once the client receives the response, it immediately sends the request again, forming a new pending request.
    • Advantages: Compared with polling, unnecessary network requests are reduced and network overhead is reduced.
    • Disadvantages: The server needs to maintain a large number of pending requests, which takes up more resources and is not suitable for high-concurrency scenarios.
    • Applicable scenarios: Suitable for scenarios where data updates are infrequent but require relatively high real-time performance.
  3. WebSocket:

    • Working principle: WebSocket is a full-duplex communication protocol. By establishing a persistent connection, the client and server can send and receive messages at any time. After the connection is established, both parties can send messages directly without frequent handshaking.
    • Advantages: realize real-time communication, reduce unnecessary network overhead, high performance, and support cross-domain communication.
    • Disadvantages: Both the server and the client need to support the WebSocket protocol.
    • Applicable scenarios: Suitable for scenarios that require real-time communication, such as real-time chat, online games, etc.
  4. Server-Sent Events(SSE):

    • How it works: SSE is a one-way communication protocol that allows the server to send data to the client, but the client cannot send data to the server. The client EventSourcesubscribes to the server's event stream through the object, and once new data is available, the server will automatically send the data to the client.
    • Advantages: Simple implementation, no two-way handshake like WebSocket, suitable for server to push data to client.
    • Disadvantage: only supports one-way communication, not suitable for client to send request to server.
    • Applicable scenarios: Applicable to scenarios where the server actively pushes real-time data to the client, such as push notifications, real-time monitoring, etc.

How does the front end use WebSocket?

Using WebSocket in the front end is very simple, first you need to create a WebSocket object in the browser, and then establish a connection with the server through this object. Once the connection is successfully established, the front end can communicate with the server in real time by sending and receiving messages.

1. Create a WebSocket object

In JavaScript, a WebSocket object can be created by the following code:

const socket = new WebSocket('ws://example.com'); // 根据实际情况替换为服务器的 WebSocket 地址

In the above code, we create a WebSocket object and pass in the server's WebSocket address as a parameter. The protocol of the WebSocket address can be ws(unencrypted) or wss(encrypted).

2. Listen to events

Once the WebSocket connection is successfully established, the connection status and message sending and receiving can be handled by listening to events.

socket.onopen = () => {
    
    
  console.log('WebSocket连接已建立');
};

socket.onmessage = event => {
    
    
  const message = event.data;
  console.log('收到消息:', message);
};

socket.onclose = () => {
    
    
  console.log('WebSocket连接已关闭');
};

socket.onerror = error => {
    
    
  console.error('WebSocket连接错误:', error);
};

In the above code, we listened to onopenthe event (connection established), onmessageevent (message received), oncloseevent (connection closed), onerrorevent (connection error). Whenever the corresponding event is triggered, we handle the corresponding logic through the callback function.

3. Sending and receiving messages

Once the WebSocket connection is successfully established, you can send()send messages through the method and onmessagereceive messages through the event.

// 发送消息
socket.send('Hello, WebSocket!');

// 接收消息在上面的监听代码中已经处理

The above code demonstrates how to create a WebSocket connection, send and receive messages in the front end. When the server and client are connected, they can communicate in real time through send()methods and events at any time.onmessage

4. The heartbeat mechanism of websocket

The role of the WebSocket heartbeat mechanism mainly includes the following aspects:

  1. Keep the connection alive :
    WebSocket is a two-way communication protocol. Once the connection is established, data can be transmitted in real time between the server and the client. However, due to network and other reasons, the connection may be closed if there is no data transmission for a long time. The heartbeat mechanism can keep the connection active and prevent the connection from being interrupted by sending heartbeat packets periodically, even if there is no actual data interaction.

  2. Confirm the survival status of the server :
    Through the heartbeat mechanism, the client can periodically send heartbeat packets to the server and wait for the server's response. If no response from the server is received within a period of time, the client can judge that the server may be faulty or disconnected, and perform corresponding processing according to the situation, such as reconnecting to the server.

  3. Optimize network resource utilization :
    The heartbeat mechanism can send smaller data packets at regular intervals. Compared with the transmission of large amounts of data, heartbeat packets occupy less resources. This helps to reduce the waste of network resources and improve data transmission efficiency.

  4. Error handling and reconnection :
    Through the heartbeat mechanism, the client can detect the disconnection in time, and perform error handling and reconnection operations. In the case of an unstable network environment or a server failure, the heartbeat mechanism can help the client to restore the connection to the server faster.

  5. Connection status monitoring :
    The heartbeat mechanism can be used to monitor the status of WebSocket connections, including connection establishment, disconnection, and abnormal states. This helps the client understand the connection status and act accordingly.

In general, the role of the WebSocket heartbeat mechanism is to maintain the stability and reliability of the connection, to ensure that the connection remains active, and to deal with abnormal situations in a timely manner, so as to improve communication efficiency and user experience.
use:

const webSocketUrl = 'ws://example.com'; // WebSocket服务器地址
const heartBeatInterval = 5000; // 心跳间隔时间,单位为毫秒

let webSocket = null;
let heartBeatTimer = null;

function initWebSocket() {
    
    
  webSocket = new WebSocket(webSocketUrl);

  webSocket.onopen = () => {
    
    
    console.log('WebSocket连接已建立');

    // 建立连接后开始发送心跳包
    startHeartBeat();
  };

  webSocket.onmessage = (event) => {
    
    
    // 处理服务器发送的消息
    console.log('收到服务器消息:', event.data);
  };

  webSocket.onclose = () => {
    
    
    console.log('WebSocket连接已关闭');

    // 连接关闭后停止心跳包
    stopHeartBeat();
    
    // 可根据需要重新连接
    // reconnect();
  };
}

function startHeartBeat() {
    
    
  // 每隔一段时间发送心跳包
  heartBeatTimer = setInterval(() => {
    
    
    if (webSocket.readyState === WebSocket.OPEN) {
    
    
      webSocket.send('ping'); // 发送心跳包
    }
  }, heartBeatInterval);
}

function stopHeartBeat() {
    
    
  // 停止心跳包发送
  clearInterval(heartBeatTimer);
}

// 初始化WebSocket连接
initWebSocket();

the case

Realize a simple chat function
1. Create a folder
2. Initialize

npm init -y
npm install websocket

3. Create a websocket server and name it server.js

const websocket=require("websocket").server
const http=require('http');
const httpServer = http.createServer().listen(8080, ()=>{
    
    
    console.log('cyl: ','http://localhost:8080');
})
const websocketServer = new websocket({
    
    
    httpServer: httpServer,
    autoAcceptConnections: false
})
const conArr = []
websocketServer.on('request', function(request) {
    
    
	// 这就是一次客户端发送的消息
	// websocket 需要将这个链接保存起来
	// 只要客户端和服务器没有断开,这个链接必须在
 	// 客户端与服务端的通信都是从这个链接上通信
	const connection = request.accept()

	// 每次接收一个链接,将它存放在数组里面
	conArr.push(connection)
	console.log(connection)

	// 监听客户端发送的消息
	connection.on('message', function(message) {
    
    
    	console.log(message);
 		// 发送消息给客户端(广播到各个客户端)
  		// 后面加上 utf8Data 编码
 		// 要将所有的链接全部发出去,才可以让每个客户端接收到其他传来的数据
  		for(let i = 0; i < conArr.length; i++) {
    
    
   			conArr[i].send(message.utf8Data)
   		}
	})
})

4. Create the file index.html sent to the client

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <!-- 需要一进入浏览器就要建立链接 -->
  <!-- 点击按钮发送消息给服务器 -->
  输入姓名:<input type="text" id="uName">
  <br>
  输入消息:<input type="text" id="context">

  <button id="btn"> 点击发送消息 </button>

  <div id="charRoom"></div>

  <script>
    // 用户名
    const uName = document.getElementById('uName')
    // 文本框内容
    const context = document.getElementById('context')
    // 点击按钮
    const btn = document.getElementById('btn')
    // 要显示聊天室的区域
    const charRoom = document.getElementById('charRoom')
    
    // 实例化 websocket
    // 必须加 'ws://localhost:8080' ws 协议,后面是开启的服务端接口
    const websocket = new WebSocket('ws://localhost:8080')
    // 打开事件
    websocket.onopen = function() {
      
      
      // 获取当前链接的状态
      // 1 是建立了链接
      console.log(websocket.readyState);
    }

    // 点击发送消息的事件
    btn.onclick = function() {
      
      
      // 将用户名和要发送的内容放在一个对象中,一起传送给后端
      const values = {
      
      
        uName: uName.value,
        context: context.value
      }

      // 清空文本框的内容
      uName.value = ''
      context.value = ''

      // 通过 websocket发送消息
      websocket.send(JSON.stringify(values))
    }

    // 接收服务器返回的消息
    websocket.onmessage = function(data) {
      
      
      console.log("服务器返回的数据",data)
      // 服务器返回过来的聊天信息
      const chatS = JSON.parse(data.data)

      // 添加到页面上
      charRoom.innerHTML += `
        <strong>${ 
        chatS.uName}:</strong>
        <span>${ 
        chatS.context}</span>
        <br />
      `
    }

    // 服务器断开连接,客户端会触发
    websocket.onclose = function() {
      
      }
  </script>
</body>
</html>

4. Start the server

node server.js

Service started successfully
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/CYL_2021/article/details/131883243