Based on the WebSocket communication Implementation of Node. js, node. jswebsocket

Source: Internet
Author: User

Based on the WebSocket communication Implementation of Node. js, node. jswebsocket

Node dependency package

There are many dependency packages for implementing Websocket in node. Both websocket and ws can be used. This article selects ws for implementation. First install the dependency

npm install ws

Chat Room instance

Assume that users A, B, C, and D are connected to the Websocket service through the client, and all messages sent by each user must be forwarded to others through Websocket, this scenario is similar to the scenario where the server broadcasts messages of A to other users in the group.

Server implementation

First, let's look at the server program. The specific workflow consists of the following steps:

  1. Create a WebSocketServer service and listen to connection requests from port 8080.
  2. Whenever a new client successfully connects to the WebSocket, the connection is pushed to the array of the connection pool.
  3. Listen for message events. When this event occurs, traverse the connection pool and forward the message to the corresponding client in connection units.
  4. Listen for the close event. When this event occurs, remove the connection from the connection pool.

Server 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 the message clients. forEach (function (ws1) {if (ws1! ==Ws) {ws1.send (message) ;}}); ws. on ('close', function (message) {// when the connection is closed, remove it from the connection pool clients = clients. filter (function (ws1) {return ws1! = Ws })});});

Client implementation

How to discover users?

Through the demo above, we can see that WebSocket is based on connections, that is, we know that data is sent from that connection, but we do not know that the client is Li Lei or Han Meimei, how can this be done? In another scenario, Li Lei only wants to send messages to Han Meimei and does not want to broadcast the messages to other clients. At this time, we need to be able to identify the correspondence between user identities and connections on the Server side.

Therefore, after the client connects to WebSocket, a request is sent again to tell the Server what the user_id is, and the Server stores the relationship between the user_id and connection in hashmap, at this point, the ing between user_id and connection is established. To send a message to the corresponding client, retrieve the connection information of the corresponding user from hashmap and call the send method to send the message.

Dependency package

npm install hashmap

Server implementation

var WebSocketServer = require('ws').Server, webSocketServer = new WebSocketServer({port: 8080});var HashMap = require('hashmap');// record the clientvar userConnectionMap = new HashMap();var connectNum = 0;// connectionwebSocketServer.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']);  });});

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.