Bolboa Bolboa - 2 years ago 141
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}),

wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', 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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download