[英]Tornado - Listen to multiple clients simultaneously over websockets
我想使用Tornado在Python中创建Websocket服务器。 这是API: http : //tornado.readthedocs.org/en/latest/websocket.html
在API中,我看不到用于获取客户端句柄的选项。 如何同时处理多个客户端连接?
例如, on_message(self, message)
方法直接给出消息。 不包含已连接客户端的任何句柄。
我希望接收客户端请求,进行一些处理(这可能需要很长时间),然后回复给客户端。 我正在寻找一个客户端句柄,以后可以用来回复。
据我了解,您想要这样的东西:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.