简体   繁体   English

Socket.io向特定用户发出

[英]Socket.io emit to specific user

I have two clients: Client 1 and Client 2. Client 1 sends a message to Client 2 specifically without broadcasting the message to the rest of the clients. 我有两个客户端:客户端1和客户端2.客户端1专门向客户端2发送消息,而不向其余客户端广播消息。

From Client 1: 来自客户1:

var socket = io();

socket.on("connect", () => {  
  button.addEventListener("click", function() {
     socket.emit("send", {room, message, client1_id, client2_id});
  })
})

Client 2 sends its socket.io session id to the backend first, and awaits for the backend to emit to Client 2 specifically: 客户端2首先将其socket.io会话ID发送到后端,并等待后端特别向客户端2发送:

var socket = io();

socket.on("connect", () => {
  socket.emit("send_id", (socket.io.engine.id))
  socket.on(client2_id, (data) => {
    console.log(data);
  })
})

Node.js backend: Node.js后端:

var tech = io.of("/");

tech.on("connection", (socket) => {
  var receiver_id;
  socket.on("send_id", (data) => {
    receiver_id = data;
  })
  socket.on("send", data => {
    io.to(receiver_id).emit(data.client2_id, "hello");
  })
})

There is no console.log at Client 2 at the end, if I load Client 1 and 2 both together, then click on the button. 最后,客户端2上没有console.log,如果我同时加载客户端1和2,则单击按钮。

Could somebody tells me what it is wrong here, please? 有人能告诉我这里有什么不对吗?

Thanks for your help. 谢谢你的帮助。

When Client 1 send emit event, the event will be handle by thread of Client1. 当Client 1发送emit事件时,该事件将由Client1的thread处理。

This mean, in line io.to(receiver_id).emit(data.client2_id, "hello"); 这意味着,在行io.to(receiver_id).emit(data.client2_id, "hello"); , there receiver_id is id of Client1's socket. receiver_id是Client1的套接字的id。

receiver_id variable is not necessary because you have receiver id in data . receiver_id变量不是必需的,因为您在data有接收者ID。

Try use my snippet code: 尝试使用我的代码段代码:

io.to(data.client2_id).emit(data.client2_id, "hello"); // I think it will be better if you change event name to `direct-message` instead of `data.client2_id`

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

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