使用socket.io和node.js将消息发送到特定客户端 [英] Send message to specific client with socket.io and node.js

查看:137
本文介绍了使用socket.io和node.js将消息发送到特定客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:

client.send(message, receiverSessionId)

但是 .send() .broadcast()方法似乎都没有供应我需要。

But neither the .send() nor the .broadcast() methods seem to supply my need.

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

What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.

任何想法?

推荐答案

你必须抓住客户端(惊喜),您可以采用简单的方式:

Well you have to grab the client for that (surprise), you can either go the simple way:

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

哪个可能会破,我几乎不怀疑它,但总是有可能 io.clients 可能会被更改,因此请谨慎使用上述内容

Which may break, I hardly doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

或您自己跟踪客户端,因此您将它们添加到连接侦听器中您自己的客户端对象并删除它们在 disconnect 监听器中。

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.

我会使用后者,因为根据您的应用程序,您可能希望拥有无论如何,对于客户来说更多的状态,所以类似 clients [id] = {conn:clientConnect,data:{...}} 可能会完成这项工作。

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

这篇关于使用socket.io和node.js将消息发送到特定客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆