我想要将数据发送到一个特定的套接字ID。
在旧版本中,我们曾经能够做到这一点:
io.sockets.socket(socketid).emit('message', 'for your eyes only');
我该如何在Socket.IO 1.0中做类似的事情呢?
发布于 2014-06-15 04:45:57
在socket.io 1.0中,它们为此提供了更好的方法。每个socket通过自己的id自动加入一个默认房间。检查文档:http://socket.io/docs/rooms-and-namespaces/#default-room
因此,您可以使用以下代码通过id将其发送到套接字:
io.to(socketid).emit('message', 'for your eyes only');
发布于 2015-04-01 21:55:01
如果你使用了一个命名空间,我发现下面的方法是可行的:
//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/
发布于 2016-10-19 03:23:52
我相信@好奇心和@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
https://stackoverflow.com/questions/24041220
复制相似问题