Ajouve Ajouve - 27 days ago 23
Node.js Question

webSocketServer node.js how to differentiate clients

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 WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
ws.send(message);
});
ws.send('something');
});


This code works fine with my client js.

But I would like to send a message to a particular user or all users having sockets open on my server.

In my case I send a message as a client and I receive a response but the others user show nothing.

I would like for example user1 sends a message to the server via webSocket and I send a notification to user2 who has his socket open.

Answer Source

You can simply assign users ID to an array CLIENTS[], this will contain all users. You can directly send message to all users as given below:

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

wss.on('connection', function(ws) {
    CLIENTS.push(ws);
    ws.on('message', function(message) {
        console.log('received: %s', message);
        sendAll(message);
    });
    ws.send("NEW USER JOINED");
});

function sendAll (message) {
    for (var i=0; i<CLIENTS.length; i++) {
        CLIENTS[i].send("Message: " + message);
    }
}