将消息发送到Socket.IO 1.0中的特定ID

将消息发送到Socket.IO 1.0中的特定ID,socket.io,socket.io-1.0,Socket.io,Socket.io 1.0,我想将数据发送到一个特定的套接字ID 我们以前在旧版本中可以做到这一点: io.sockets.socket(socketid).emit('message', 'for your eyes only'); 在Socket.IO 1.0中如何执行类似的操作?在Socket.IO 1.0中,您可以使用以下代码执行此操作: if (io.sockets.connected[socketid]) { io.sockets.connected[socketid].emit('message',

我想将数据发送到一个特定的套接字ID

我们以前在旧版本中可以做到这一点:

io.sockets.socket(socketid).emit('message', 'for your eyes only');

在Socket.IO 1.0中如何执行类似的操作?

在Socket.IO 1.0中,您可以使用以下代码执行此操作:

if (io.sockets.connected[socketid]) {
    io.sockets.connected[socketid].emit('message', 'for your eyes only');
}
io.to(socketid).emit('message', 'for your eyes only');
更新:


@MustafaDokumacı的答案包含了一个更好的解决方案。

在socket.io 1.0中,它们提供了一个更好的方法。每个插座都会根据自身id自动加入默认房间。检查文档:

因此,您可以通过id向套接字发送以下代码:

if (io.sockets.connected[socketid]) {
    io.sockets.connected[socketid].emit('message', 'for your eyes only');
}
io.to(socketid).emit('message', 'for your eyes only');

@Mustafa Dokumacı和@好奇已经提供了足够的信息,我正在添加如何获取套接字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');
//定义名称空间
var nsp=io.of(“/my namespace”); //将消息定向到套接字id
nsp.to(预期收件人的套接字id).emit('private message','hello');
有关名称空间的详细信息:

我相信@好奇号和@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连接)部件中。。我使用的代码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);
  });
});

to(房间id)和(用户id)之间有区别吗?实际上,我用它向一个可以有一个或多个用户的房间发送消息。“这使得向其他套接字广播消息变得很容易:”,那么可以是一个或多个,而不是唯一的私有套接字。@WashingtonBotelho,套接字ID通常看起来像“Uj5CRqZ5b_Xubx9sAAAA”,因此理论上在这样的房间中可能有多个用户,但在实践中,我不知道在什么情况下我会将一个用户添加到其他用户的私人房间。我们如何通过他们的socketId来识别一个特定用户,这是否意味着我们需要在某个地方存储一对用户(例如用户名)和socketId?@Mustafa Dokumacımerhaba,bana bir Yardime,这太不逻辑了。。。为什么不为我们提供一种方法,向套接字id号发送消息,就这样?无论如何,在2.x上唯一有效的解决方法这个答案和更好的答案之间的区别是,使用这个解决方案,你可以有很好的回调。但是对于io.to(socketid),您不能使用回调。