讨论:使用 node.js / socket.io 实现聊天室的最佳方法?
我并不是在谈论一般的聊天应用程序,而是具体谈论聊天室的实现。
所以在node.js/socket.io中,我想到了两种方法
为每个聊天室创建一个数组,向数组中的所有用户广播消息
向所有用户广播所有消息,在客户端电脑上确定他们是否属于聊天室,如果是,则接受消息。
1 的弱点是,最终当你扩展时,你会用数组对象淹没服务器的内存,而我在我的主机上只使用了大约 80mb。
2 的弱点在于,向每个人广播最终成本高昂,而且淹没客户的机器也不会让他们满意。
我确信有更好的方法来实现聊天室,所以这就是为什么我请求你们帮助我。我首先寻求服务器端的性能,然后是客户端的性能,并且它必须是可扩展的。
I'm not really talking about the general chat app, but rather specifically about the chatroom implementation.
So in node.js/socket.io, I thought of two approaches
Create an array for each chatroom, broadcast message to all users in array
Broadcasts all messages to all users, on clients' PCs determine if they belong in chatroom, if so, accept the message.
The weakness in 1 is that eventually as you scale up you will flood the server's memory with array objects, and I using only about 80mb on my hosting.
The weakness in 2 is that broadcasting to everyone is costly eventually and flooding the clients' machines won't make them happy.
I'm sure there are better approaches on how to implement the chatroom, so that's why I'm asking you guys to help me. I'm looking for performance on the server-side first then client-side, and it must be scalable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Socket.IO 0.7+ 引入了房间概念。这可能就是您正在寻找的东西。
因此,无需为特定房间的用户管理自己的阵列,socket.io 内置了此功能。
Socket.IO 0.7+ introduced a rooms concept. This is probably the thing you are looking for.
So no need to manage your own array with users for specific rooms, socket.io has this build in.
我在这里做了类似的事情:
http://davidgranado.com/demos/chat_shuffle/
你可以测试它通过打开几个窗口并与自己聊天,因为每个实例都被视为一个人(这是我的第一个节点应用程序)。
它的工作方式是每个人都与另一个人配对进行对话。实际上,每个人都在一个两人房间里。
为了传达消息,我将用户注册为彼此关联,并且仅将其发送给一位合作伙伴 Chatter。这个想法可以很容易地扩展到任意数量的人以将聊天者联系起来。这样,您就不必向每个人进行浪费的广播。
I did something similar here:
http://davidgranado.com/demos/chat_shuffle/
You can test it out by opening up several windows and chatting with yourself since each instance is considered a person (it's my first node app).
The way it works is that every person is paired up with another person for a conversation. Effectively, everyone is in a two person room.
To get the messages across, I register the users as being associated with each other and only send it to the one partner chatter. This idea can easily be expanded out any number of people to associate the chatters. That way, you don't have to do a wasteful broadcast to everyone.
Now.js 将使这变得更加容易: http://nowjs.com/guide - 他们的指南已经有了如何操作以及他们的 github 存储库 https://github.com/Flotype/now/tree/master/examples/multiroomchat_example
Now.js will make this much easier: http://nowjs.com/guide - their guide already has a how to, as well as their github repo https://github.com/Flotype/now/tree/master/examples/multiroomchat_example