Bolboa Bolboa - 6 months ago 24
Node.js Question

Find current client (websocket)

I am using something like the following code to save all clients in an array...

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);
findClient(message);
});
ws.send("NEW USER JOINED");
});

function findClient (message) {
for (var i=0; i<CLIENTS.length; i++) {
//this is where I'm stuck
if current client then return i
}
}


I do not know what to put inside the for loop to find the current client. I want to iterate through the array, and if the current client == one of the client in the array, I want to return its index.

I'm sure there is a simple way to do this, but I am stuck.

Answer

Do findClient(ws) -- you already have the ws (socket) belonging to that particular client bound to the closure of the message event handler. Then the findClient function becomes:

function getClientIndex(socket) {
  return CLIENTS.indexOf(socket);
}
Comments