简体   繁体   中英

Socket.IO emit data into a room to myself

I'm building a chat application in which I want to load on start the last messages between 2 users.

Here's what I do on the frontend so load the old messageList from the database:

socket.emit('get messageList', data);

on the backend side I load the messages into messages and try to emit them back. I dont want to broadcast.emit since I want to load the data in my session, not in the chat partners.

socket.in(roomId).emit('send messageList', messages);

When I execute this code the messageList of the chat partner gets refreshed. Basically it has the same effect as

socket.in(roomId).broadcast.emit('send messageList', messages);

Before I implemented the rooms a normal

socket.emit('send messageList', messages);

would update my list just as I'd expected. But since I use the code with rooms it doesn't work anymore.

My questions:

  • Why is that?
  • Is it possible to send back data from the backend to the client with socket.io?
  • Or am I doing something completely wrong?

I'll make my comment into an answer since that seems to be what will work for you.

If you're just trying to respond to the client that send you a request, you just socket.emit() back to the requesting socket. You're just trying to respond to the sender so you don't do anything differently just because there are chat rooms being used. The response goes to the socket that asked for it, regardless of chat room usage.

To send to a single client, you just send to that client's socket. You only use chat rooms to help with the sending if you want to send to all clients in that room or all clients in the room except one.

socket.nsp.to(room).emit('room_message','hello world')

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