X
X
XiNull2021-09-08 10:02:05
JavaScript
XiNull, 2021-09-08 10:02:05

How to get data by key wss.clients without enumeration of all users?

Hello. We are talking about the server (WebSocket).
In wss.clients all users, in order to get information about a specific user, you have to iterate and compare all of them:

const WebSocket = require('ws');
const wss = new WebSocket.server({ port:8080 });
...
wss.clients.forEach(function each(client) {
  if(id === client.id) {
        console.log('ID: ' + client.id)
        console.log('KEY:' + client. key)
   }
})

Is it possible to somehow get data by a specific id or key without enumeration of all connected users?
PS wss.clients is not an array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuriy Vorobyov, 2021-09-08
@XiNull

You can create your own object for storing users and save the Id there when connecting, then you can refer to specific users

myClients = [];
wss.on('connection', function(ws) {
    myClients.push(ws);
});

You can also dig in the socket.io git , this is a wrapper over standard sockets, I think you can find a more correct and scalable solution there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question