node.js socket.io 如何发送到特定客户端?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10110411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:30:57  来源:igfitidea点击:

node.js socket.io How to emit to a particular client?

node.jssocket.io

提问by srinathhs

I want to "emit" a message to a particular client which is selected based on another message received in a different client, How do I do this?

我想向特定客户端“发送”一条消息,该消息是根据在不同客户端收到的另一条消息而选择的,我该怎么做?

I am thinking of joining each client to their own "room" and then broadcast. Is there a better way?

我正在考虑将每个客户加入他们自己的“房间”然后进行广播。有没有更好的办法?

回答by Francesco Laurita

UPDATE for socket.io version 1.0 and above

socket.io 1.0 及以上版本的更新

io.to(socketid).emit('message', 'whatever');

For older version:

对于旧版本:

You can store each client in an object as a property. Then you can lookup the socket based on the message:

您可以将每个客户端作为属性存储在一个对象中。然后您可以根据消息查找套接字:

var basket = {};

io.sockets.on('connection', function (socket) {
  socket.on("register", function(data) {
    basket[data.nickname] = socket.id;
  });
  socket.on("privmessage", function(data){
    var to = basket[data.to];
    io.sockets.socket(to).emit(data.msg);
  });
});

Not tested...but it should give you an idea

未测试......但它应该给你一个想法

回答by Minho Lee

For socket.io version 1.0 use:

对于 socket.io 1.0 版使用:

io.to(socketid).emit('message', 'whatever');

回答by Willem van der Veen

Emitting to a particular client using a socketID.

使用 socketID 发送到特定客户端。

Server/ package: socket.io:

服务器/包:socket.io:

io.to(socketID).emit('testEvent', 'yourMessage');

Client/ package socket.io-client:

客户端/包 socket.io-client:

io.sockets.on('connection',(socket) => {
  socket.on("testEvent", data => {
    console.log(data);
  });
});

You can get access the socketID in the following manner:

您可以通过以下方式访问 socketID:

io.on('connection', (socket, next) => {
    const ID = socket.id // id property on the socket Object
})

It is simply a property on the socketobject

它只是socket对象上的一个属性

回答by Michael Pigle

For socket.io v1.0< use:

对于 socket.io v1.0< 使用:

io.to(socketID).emit('testEvent', 'yourMessage');

io.to(socketID).emit('testEvent', 'yourMessage');