【发布时间】:2014-07-25 07:50:30
【问题描述】:
我想将数据发送到一个特定的套接字 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 中做类似的事情?
【问题讨论】:
在 socket.io 1.0 中,它们为此提供了更好的方法。每个套接字都通过 self id 自动加入一个默认房间。查看文档:http://socket.io/docs/rooms-and-namespaces/#default-room
因此您可以使用以下代码通过 id 向套接字发出:
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 获取套接字并向其发射的最佳方式。
【讨论】: