webSocketServer node.js how to differentiate clients

后端 未结 10 2068
[愿得一人]
[愿得一人] 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

    In nodejs you can directly modify the ws client and add custom attributes for each client separately. Also you have a global variable wss.clients and can be used anywhere. Please try the next code and try to connect at leat two clients:

    var WebSocketServer = require('ws').Server;
    var wss = new WebSocketServer({
        server: httpsServer
    });
    
    
    wss.getUniqueID = function () {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }
        return s4() + s4() + '-' + s4();
    };
    
    wss.on('connection', function connection(ws, req) {
        ws.id = wss.getUniqueID();
    
        wss.clients.forEach(function each(client) {
            console.log('Client.ID: ' + client.id);
        });
    });
    

    You can also pass parameters directly in the client connection URL:

    https://myhost:8080?myCustomParam=1111&myCustomID=2222

    In the connection function you can get these parameters and to assign these parameters directly to your ws client:

    wss.on('connection', function connection(ws, req) {
    
        const parameters = url.parse(req.url, true);
    
        ws.uid = wss.getUniqueID();
        ws.chatRoom = {uid: parameters.query.myCustomID};
        ws.hereMyCustomParameter = parameters.query.myCustomParam;
    }
    

提交回复
热议问题