Ws: Saving reference to ws

Created on 19 Feb 2018  路  6Comments  路  Source: websockets/ws

Hi
I am making a voip app and want to save users sockets in memory probably in redis. I want to ask how can I save ws references in redis? Each users can have multiple sockets at a time (logged in from different devices) and I want to send message to that user's sockets. Is there any id etc of socket that I can save that be used again to send message to that user?

Most helpful comment

const map = new Map();

wss.on('connection', (ws) => {
  const id = uuid.v4();
  map.set(id, ws);
  ws.on('close', () => map.delete(id));
});

function getSocketByid(id) {
  return map.get(id);
}

Please use SO for this kind of questions.

All 6 comments

There is no id, but you can add it yourself if needed, see https://github.com/websockets/ws/issues/859#issuecomment-253197752

Ok I can assign an id to the socket but if I have an id of socket that belongs to user how can I send message via that socket if I only know its id?

const map = new Map();

wss.on('connection', (ws) => {
  const id = uuid.v4();
  map.set(id, ws);
  ws.on('close', () => map.delete(id));
});

function getSocketByid(id) {
  return map.get(id);
}

Please use SO for this kind of questions.

Haha thanks a lot. Sorry for bothering. I wanted to ask if there is some built in function like socket.io for this. Thanks a lot for helping :)

No, there isn't. This library only implements the WebSocket API and nothing else. If you need more advanced features use a framework like Socket.IO, Primus, SocketCluster, etc.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

HanHtoonAung picture HanHtoonAung  路  3Comments

robertmylne picture robertmylne  路  3Comments

brainkim picture brainkim  路  4Comments

NodePing picture NodePing  路  5Comments

ORESoftware picture ORESoftware  路  3Comments