Search code examples
node.jssocket.iosocketserver

How to implement sending messages to some user not to all sockets


How to send message instead to all clients in room, to specific user in default room based on username or id. Where I need to implement that, only on server site or? I know I am doing wrong and I am confused.

var numUsers = 0;

io.on('connection', (socket) => {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', (data) => {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

I see in docs that code https://socket.io/docs/rooms-and-namespaces/ and how can I handle the ID for users, they changed in every re-connection


Solution

  • Here is what you can do:

    1.You can use your own data structure to store users information like socketId and other things or go for redis it is a good in memory data structure.

    2.You have to store socketId for each user when a new connection is made on server using any of the above or some other method.

    3.when you want to send the message to a particular user you need have it's socketId and use this code to send message:

     io.to(`${socketId}`).emit('hey', 'How are you');
    

    4.When a user disconnects just delete the user's info like socketId and other info which you have.

    So, when a user join your server save his info and when he leaves just delete it.

    Now suppose you have four users connected on your server. just create a array of object to keep the track of users and socket ids. when new user connects just push into the array and when a user exit just loop through the array and when socketId matches just remove that object from array simple

     let users = [{name:'a',id:'socketId'},{name:'b',id:'socketId'},{name:'c',id:'socketId'},{name:'d',id:'socketId'}]
    

    if you want to send message to user b only just loop through the array and match the name property and when you find the matching name just fetch the id of that user and send it away

    for(let i=0 ; i<users.length ; i++){
         if(users[i].name == 'b'){
            io.to(users[i].id).emit('hey', 'How are you');
         }
    }