WebSocket 服务器的最佳实践是什么? [英] What is the best practice for WebSocket server(s)?

查看:40
本文介绍了WebSocket 服务器的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个网站,用户可以在其中打开聊天室.打开房间后,用户可以邀请其他人聊天.

Lets say you have a site where users may open chat rooms. Once a room is opened, the users may invite others and chat.

假设您想使用 WebSockets 与客户端进行通信.在大多数服务器端 WebSocket 实现中,有一个简单的函数,如 connection.broadcast(message),它将消息发送到所有连接的主机,但不是发起广播的主机.这是一个很棒的功能,因为您不需要为自己保留所有客户的列表来保持更新.聊天室示例的问题在于,在这种情况下,您不想向所有人广播每条消息,而只想向同一房间中的其他客户端广播.

Lets also pretend you want to use WebSockets for the communication with the clients. In most server-side WebSocket implementations there is a simple function like connection.broadcast(message) which sends messages to all connected hosts, but not the one who initiated the broadcast. This is a great feature, because you don't need to keep a list of all clients for your self, to keep them updated. The problem with the chat room example is that, in this case, You don't want to broadcast every message to everyone, but only to the other clients who are in the same room.

这让我有两个选择:

  • 滚动我自己的 broadcastToRoom(room_id) 函数,这意味着跟踪所有客户和房间.
  • 每次创建新房间时都会生成一个新的服务器实例(在新端口上).
  • Roll my own broadcastToRoom(room_id) function, which in turn means to track all clients and rooms.
  • Spawn a new instance of the server (on a new port) every time a new room gets created.

你会怎么做?

推荐答案

只需为每个房间滚动您自己的 broadcast 版本,您会保留该房间中的用户列表,如果有人发送进入/发送到该房间的消息只需将其发送给房间中的所有用户,然后根据您的协议,您可以排除消息的原始发件人.

Just roll your own version of the broadcast for each room you keep a list of users in that room, and if someone sends a message in/to that room just send it to all the users in the room, depending on your protocol you can then exclude the original sender of the message.

无论如何,您都有每个房间的用户列表,因此您只需将连接作为属性添加到用户对象即可.

You have a list of users for each room anyway, so you can just add the connection as a property to the user object.

但请记住,由于最近发现"了当前 WebSocket 规范的安全问题,Opera 和 Mozilla 都禁用了对 WebSocket 的支持,直到发布新版本.因此,WebSockets 需要更多时间才能广泛使用,并且服务器需要更改为新版本.

But keep in mind that due to recently "discovered" security problem with the current WebSocket specification, both Opera and Mozilla have disabled support for WebSocket until a new version has been issued. So it will take some more time for WebSockets to have widespread availability and server needs to change to with the new version.

详情见:
http://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/
http://blog.pusherapp.com/2010/12/9/it-s-not-websockets-it-s-your-broken-proxy

这篇关于WebSocket 服务器的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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