简体   繁体   English

Socket.IO将数据发送到我自己的房间

[英]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: 这是我在前端执行的操作,因此从数据库中加载旧的messageList:

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

on the backend side I load the messages into messages and try to emit them back. 在后端,我将消息加载到messages然后尝试将它们发回。 I dont want to broadcast.emit since I want to load the data in my session, not in the chat partners. 我不想broadcast.emit因为我想在会话中而不是在聊天伙伴中加载数据。

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

When I execute this code the messageList of the chat partner gets refreshed. 当我执行此代码时,聊天伙伴的messageList会刷新。 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? 是否可以使用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. 如果您只是想响应发送请求的客户端,则只需将socket.emit()返回到请求的套接字即可。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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