使用socket.io和node.js将消息发送到特定客户端

JavaScript Node.js

卡卡西Near

2020-03-24

我正在使用socket.io和node.js,直到现在看起来还不错,但我不知道如何从服务器向特定客户端发送消息,如下所示:

client.send(message, receiverSessionId)

但是无论是.send()还是.broadcast()方法似乎都无法满足我的需求。

我发现一种可能的解决方案是,该.broadcast()方法将不发送消息的SessionId数组作为第二个参数,因此我可以将此时连接了所有SessionId的数组传递给服务器,除了那个我希望发送邮件,但是我觉得必须有一个更好的解决方案。

有任何想法吗?

第3171篇《使用socket.io和node.js将消息发送到特定客户端》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
路易Davaid 2020.03.24

Socket.IO允许您“命名”套接字,这实际上意味着分配不同的端点或路径。

这可能会有所帮助:http : //socket.io/docs/rooms-and-namespaces/

伽罗理查德 2020.03.24

io.sockets.sockets [socket.id] .emit(...)在v0.9中为我工作

GO 2020.03.24

在1.0中,您应该使用:

io.sockets.connected[socketid].emit();
小宇宙 2020.03.24

好吧,您必须为此赢得客户(惊喜),您可以采用以下简单方法:

var io = io.listen(server);
io.clients[sessionID].send()

我怀疑这可能会中断,但是它总是有io.clients可能被更改,因此请谨慎使用以上内容

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android