webSocketServer node.js how to differentiate clients

后端 未结 10 1929
[愿得一人]
[愿得一人] 2020-12-22 19:36

I am trying to use sockets with node.js, I succeded but I don\'t know how to differentiate clients in my code. The part concerning sockets is this:

var WebSo         


        
10条回答
  •  生来不讨喜
    2020-12-22 20:18

    It depends which websocket you are using. For example, the fastest one, found here: https://github.com/websockets/ws is able to do a broadcast via this method:

    var WebSocketServer = require('ws').Server,
       wss = new WebSocketServer({host:'xxxx',port:xxxx}),
       users = [];
    wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
      client.send(data);
     });
    };
    

    Then later in your code you can use wss.broadcast(message) to send to all. For sending a PM to an individual user I do the following:

    (1) In my message that I send to the server I include a username (2) Then, in onMessage I save the websocket in the array with that username, then retrieve it by username later:

    wss.on('connection', function(ws) {
    
      ws.on('message', function(message) {
    
          users[message.userName] = ws;
    

    (3) To send to a particular user you can then do users[userName].send(message);

提交回复
热议问题