0

So I have a message board (my first MERN project,) and I'm trying to implement a notification feature using socket.io. Overkill I know, but I plan to expand it to include a simple chat room later.

I'm wondering if somebody would (please) explain to me how I can associate a user with a connection so that I can send a message from the server to a specific user.

Server:

io.on('connection', (socket) => {
  socket.emit('messageFromServer', { data: 'Welcome to the server' });
  socket.on('messageToServer', (dataFromClient) => {
    console.log(dataFromClient);
  });
});

client:

socket.on('messageFromServer', (data) => {
      console.log(data);
    });
    socket.emit('messageToServer', { username: appState.username });
harry young
  • 600
  • 1
  • 8
  • 24
  • I tend to send up the users JWT on the connection in a header, just like would do with any other protected resource, same tools/lib and auth process. How are you logging in the user? – Lawrence Cherone Sep 21 '20 at 19:56
  • with a JWT, but my q is how would I use that and associate it with a unique socket – harry young Sep 21 '20 at 19:59
  • For storing list of users connected to socket.io there is numerous tuts on the interwebs, from using Object.keys(io.sockets.connected) to Maps to objects and even redis depending on your setup – Lawrence Cherone Sep 21 '20 at 19:59
  • please can you link a good one? – harry young Sep 21 '20 at 20:01
  • Does this answer your question? [Socket.IO - how do I get a list of connected sockets/clients?](https://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients) – Lawrence Cherone Sep 21 '20 at 20:01
  • Not really, I only know how to message all connected clients at once, on the server... I guess I'm wondering how to identify and send to a single user? – harry young Sep 21 '20 at 20:06
  • `socket.id` contains the connected socket id for the user, so associate it in the `connection` event with the user (after you have authenticated), as said use an object/array/redis/mysql... to map it `sockets[socket.id] = {user_id: 123, username: 'foo'}` etc than to send to foo, loop over the object or do a query, then get the key/socket.id which would be foos socket id, then emit to that id. tip: just look for and do basic search for *socket.io chat example* on the interwebs and look at the code/tutorial. – Lawrence Cherone Sep 21 '20 at 20:16

0 Answers0