我想将数据发送到一个特定的套接字 ID。
我们曾经能够在旧版本中做到这一点:
io.sockets.socket(socketid).emit('message', 'for your eyes only');
我将如何在 Socket.IO 1.0 中做类似的事情?
我想将数据发送到一个特定的套接字 ID。
我们曾经能够在旧版本中做到这一点:
io.sockets.socket(socketid).emit('message', 'for your eyes only');
我将如何在 Socket.IO 1.0 中做类似的事情?
In socket.io 1.0 they provide a better way for this. Each socket automatically joins a default room by self id. Check documents: http://socket.io/docs/rooms-and-namespaces/#default-room
So you can emit to a socket by id with following code:
io.to(socketid).emit('message', 'for your eyes only');
在 socket.io 1.0 中,您可以使用以下代码执行此操作:
if (io.sockets.connected[socketid]) {
io.sockets.connected[socketid].emit('message', 'for your eyes only');
}
更新:
@MustafaDokumacı 的答案包含更好的解决方案。
@Mustafa Dokumacı 和 @Curious 已经提供了足够的信息,我正在添加如何获取套接字 ID。
要获取套接字 id,请使用socket.id:
var chat = io.of("/socket").on('connection',onSocketConnected);
function onSocketConnected(socket){
console.log("connected :"+socket.id);
}
如果您使用了命名空间,我发现以下方法有效:
//Defining the namespace <br>
var nsp = io.of('/my-namespace');
//targeting the message to socket id <br>
nsp.to(socket id of the intended recipient).emit('private message', 'hello');
有关命名空间的更多信息:http: //socket.io/docs/rooms-and-namespaces/
我相信@Curious 和@MustafaDokumacı 都提供了行之有效的解决方案。但不同之处在于,使用@MustafaDokumacı 的解决方案,消息被广播到一个房间,而不仅仅是一个特定的客户。
当请求确认时,差异很明显。
io.sockets.connected[socketid].emit('message', 'for your eyes only', function(data) {...});
按预期工作,而
io.to(socketid).emit('message', 'for your eyes only', function(data) {...});
失败了
Error: Callbacks are not supported when broadcasting
在 Node.js --> socket.io --> 有一个聊天示例可以下载 将其粘贴到行中(io on connection)部分.. 我使用的代码可以 100% 工作
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log(socket.id);
io.to(socket.id).emit('chat message', msg+' you ID is:'+socket.id);
});
});
var socketById = io.sockets.sockets.get(id);
socketById.emit("message", "hi")
这是在 v4 中通过 ID 获取套接字并向其发射的最佳方式。