简体   繁体   中英

How to let 2 socket join the same room to chat (socket.io)

I have a problem but researched many days but still do not resolve it. I do project chat user to user socket.io and nodejs. I am user A, when I click a user B on list user on app, It will let user A and B join the same room ( set roomname is (IdOfUserA)_(IdOfUserB) ). How can i do the same on server-side, please help me or show me the post with similar problem. Thanks very much.

In pseudo-code I would do something like this :

On the client side

socket.emit('chat-with-user-b', {userb : IdOfUserB}); 
socket.on('chat-with-me', function(roomID){
   // open tchat etc..
});

On the server side :

io.on("connection", function(socket){
   socket.on('chat-with-user-b', function(IdOfUserB){
      var roomID = IdOfUserB + '_' + socket.id; // create a unique room id
      socket.join(roomID); // make user A join room
      io.sockets[IdOfUserB].join(roomID); // make user B join  room
      io.sockets.in(roomID).emit('chat-with-me', roomID);  // send join event to both.
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM