溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

怎么用Node.js實(shí)現(xiàn)WebSocket通信

發(fā)布時(shí)間:2022-12-02 09:29:13 來(lái)源:億速云 閱讀:96 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容介紹了“怎么用Node.js實(shí)現(xiàn)WebSocket通信”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

node的依賴(lài)包

node中實(shí)現(xiàn)Websocket的依賴(lài)包有很多,websocket、ws均可,本文選取ws來(lái)實(shí)現(xiàn),首先安裝依賴(lài)

npm install ws

聊天室實(shí)例

假如A,B,C,D用戶(hù)均通過(guò)客戶(hù)端連接到Websocket服務(wù),其中每個(gè)人發(fā)的消息都需要將其通過(guò)Websocket轉(zhuǎn)發(fā)給其他人,此場(chǎng)景類(lèi)似于服務(wù)端將A的消息廣播給組內(nèi)其他用戶(hù)。

服務(wù)端實(shí)現(xiàn)

首先來(lái)看服務(wù)端程序,具體的工作流程分以下幾步:

  1. 創(chuàng)建一個(gè)WebSocketServer的服務(wù),同時(shí)監(jiān)聽(tīng)8080端口的連接請(qǐng)求。

  2. 每當(dāng)有新的客戶(hù)端連接該WebSocket成功時(shí),便將該連接push到連接池的數(shù)組中。

  3. 監(jiān)聽(tīng)message事件,當(dāng)該事件發(fā)生時(shí),遍歷連接池,以連接為單位將該消息轉(zhuǎn)發(fā)到對(duì)應(yīng)的客戶(hù)端

  4. 監(jiān)聽(tīng)close事件,當(dāng)該事件發(fā)生時(shí),將該連接移出連接池

服務(wù)端代碼

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

// 連接池
var clients = [];

wss.on('connection', function(ws) {
  // 將該連接加入連接池
  clients.push(ws);
  ws.on('message', function(message) {
    // 廣播消息
    clients.forEach(function(ws1){
      if(ws1 !== ws) {
        ws1.send(message);
      }
    })
  });

  ws.on('close', function(message) {
    // 連接關(guān)閉時(shí),將其移出連接池
    clients = clients.filter(function(ws1){
      return ws1 !== ws
    })
  });
});

客戶(hù)端實(shí)現(xiàn)

<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>

如何發(fā)現(xiàn)用戶(hù)?

通過(guò)上述的demo可以看到,WebSocket都是基于連接的,也就是說(shuō)我們知道data是從那個(gè)connection發(fā)過(guò)來(lái),但并不知道使用客戶(hù)端的是李雷或者韓梅梅,這可如何是好?再想另一種場(chǎng)景,李雷只想給韓梅梅發(fā)消息,不想將消息廣播給其他客戶(hù)端,此時(shí)我們就需要在Server端能夠標(biāo)識(shí)用戶(hù)身份和連接的對(duì)應(yīng)關(guān)系。

于是,需要在客戶(hù)端連接到WebSocket之后,緊接著再發(fā)一次請(qǐng)求,告訴Server我的user_id是多少,Server將此user_id與connection之間的關(guān)系存儲(chǔ)在hashmap中,至此就建立了user_id與connection的對(duì)應(yīng)關(guān)系。當(dāng)需要發(fā)送消息給對(duì)應(yīng)的客戶(hù)端,從此hashmap中取出對(duì)應(yīng)用戶(hù)的connection信息,調(diào)用其send方法發(fā)出消息即可。

依賴(lài)包

npm install hashmap

服務(wù)端實(shí)現(xiàn)

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']);
  });
});

“怎么用Node.js實(shí)現(xiàn)WebSocket通信”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI