我想使用 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)