[英]Tornado - Listen to multiple clients simultaneously over websockets
I want to use Tornado for creating a websocket server in Python. 我想使用Tornado在Python中创建Websocket服务器。 Here is the API: http://tornado.readthedocs.org/en/latest/websocket.html 这是API: http : //tornado.readthedocs.org/en/latest/websocket.html
In the APIs, I do not see an option to get a handle for the client. 在API中,我看不到用于获取客户端句柄的选项。 How do I handle multiple client connections at the same time? 如何同时处理多个客户端连接?
For example, on_message(self, message)
method directly gives the message. 例如, on_message(self, message)
方法直接给出消息。 Doesn't contain any handle for the client who has connected. 不包含已连接客户端的任何句柄。
I would want to receive client requests, do some processing (which might take a long time), and then reply back to the client. 我希望接收客户端请求,进行一些处理(这可能需要很长时间),然后回复给客户端。 I am looking for a client handle which I can use to reply back at a later time. 我正在寻找一个客户端句柄,以后可以用来回复。
As I understand you want something like this: 据我了解,您想要这样的东西:
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)
Every websocket connection has its own object from your subclassed WebSocketHandler. 每个Websocket连接都有您自己的子类WebSocketHandler中的对象。
You can even save the connection and use it elsewhere: 您甚至可以保存连接并在其他地方使用它:
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.