![](/img/trans.png)
[英]Notifications with Socket.io - how to emit to a specific user/recipient?
[英]Socket.io emit to specific user
我有两个客户端:客户端1和客户端2.客户端1专门向客户端2发送消息,而不向其余客户端广播消息。
来自客户1:
var socket = io();
socket.on("connect", () => {
button.addEventListener("click", function() {
socket.emit("send", {room, message, client1_id, client2_id});
})
})
客户端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后端:
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");
})
})
最后,客户端2上没有console.log,如果我同时加载客户端1和2,则单击按钮。
有人能告诉我这里有什么不对吗?
谢谢你的帮助。
当Client 1发送emit事件时,该事件将由Client1的thread
处理。
这意味着,在行io.to(receiver_id).emit(data.client2_id, "hello");
, receiver_id
是Client1的套接字的id。
receiver_id
变量不是必需的,因为您在data
有接收者ID。
尝试使用我的代码段代码:
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.