龙卷风-通过WebSocket同时收听多个客户端
问题内容:
我想使用Tornado在Python中创建Websocket服务器。以下是API:http
:
//tornado.readthedocs.org/en/latest/websocket.html
在API中,我看不到用于获取客户端句柄的选项。如何同时处理多个客户端连接?
例如,on_message(self, message)
method直接给出消息。不包含已连接客户端的任何句柄。
我希望接收客户端请求,进行一些处理(这可能需要很长时间),然后回复给客户端。我正在寻找一个客户端句柄,以后可以用来回复。
问题答案:
据我了解,您想要这样的东西:
class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
# other methods
def on_message(self, message):
# do some stuff with the message that takes a long time
self.write_message(response)
每个Websocket连接都有您自己的子类WebSocketHandler中的对象。
您甚至可以保存连接并在其他地方使用它:
ws_clients = []
class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
# other methods
def open(self):
if self not in ws_clients:
ws_clients.append(self)
def on_close(self):
if self in ws_clients:
ws_clients.remove(self)
def send_message_to_all(self, message):
for c in ws_clients:
c.write_message(message)