Implementation of WebSocket Communication Based on Node. js

  • 2021-08-03 08:58:48
  • OfStack

Dependency packages for node

In node, there are many dependency packages to implement Websocket. websocket and ws can be used. In this paper, ws is selected to implement, and dependency is installed first


npm install ws

Chat room example

If A, B, C and D users are all connected to Websocket service through the client, and the messages sent by each person need to be forwarded to others through Websocket, this scenario is similar to the server broadcasting A messages to other users in the group.

Server-side implementation

First of all, look at the server program. The specific workflow is divided into the following steps:

Create a service for WebSocketServer and listen for connection requests on port 8080. Whenever a new client successfully connects to the WebSocket, the connection push is added to the array of the connection pool. Listen for an message event, and when the event occurs, traverse the connection pool and forward the message to the corresponding client in units of connection Listens for close events, and when this event occurs, moves the connection out of the connection pool

Server-side code


var WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({port: 8080});

//  Connection pool 
var clients = [];

wss.on('connection', function(ws) {
  //  Add the connection to the connection pool 
  clients.push(ws);
  ws.on('message', function(message) {
    //  Broadcast message 
    clients.forEach(function(ws1){
      if(ws1 !== ws) {
        ws1.send(message);
      }
    })
  });

  ws.on('close', function(message) {
    //  When a connection is closed, move it out of the connection pool 
    clients = clients.filter(function(ws1){
      return ws1 !== ws
    })
  });
});

Client implementation


<html>
<input type="text" id="text">
<input type="button" onclick="sendMessage()" value="online">
<script>
  var ws = new WebSocket("ws://localhost:8080");

  ws.onopen = function (e) {
    console.log('Connection to server opened');
  }
  ws.onmessage = function(event) { 
    console.log('Client received a message', event); 
  }; 
  ws.onclose = function (e) {
    console.log('connection closed.');
  }
  function sendMessage() {
      ws.send(document.getElementById('text').value);
  }
</script>
</html>

How to find users?

From the above demo, we can see that WebSocket is based on connection, that is to say, we know that data is sent from that connection, but we don't know that Li Lei or Han Meimei is using the client. What can we do? Think about another scenario. Li Lei only wants to send a message to Han Meimei, but doesn't want to broadcast the message to other clients. At this time, we need to be able to identify the corresponding relationship between user identity and connection on Server.

Therefore, after the client connects to WebSocket, it is necessary to send another request to tell Server what my user_id is, and Server stores the relationship between user_id and connection in hashmap, thus establishing the corresponding relationship between user_id and connection. When you need to send a message to the corresponding client, take out the connection information of the corresponding user from this hashmap, and call its send method to send a message.

Dependency package


npm install hashmap

Server-side implementation


var WebSocketServer = require('ws').Server, webSocketServer = new WebSocketServer({port: 8080});
var HashMap = require('hashmap');

// record the client
var userConnectionMap = new HashMap();
var connectNum = 0;

// connection
webSocketServer.on('connection', function(ws) {
  ++ connectNum;
  console.log('A client has connected. current connect num is : ' + connectNum);
  ws.on('message', function(message) {
    var objMessage = JSON.parse(message);
    var strType = objMessage['type'];

    switch(strType) {
      case 'online' : 
        userConnectionMap.set(objMessage['from'], ws);
        break;
      default:
        var targetConnection = userConnectionMap.get(objMessage['to']);
        if (targetConnection) {
          targetConnection.send(message);
        }
    }
  });

  ws.on('close', function(message) {
    var objMessage = JSON.parse(message);
    userConnectionMap.remove(objMessage['from']);
  });
});


Related articles: