Tornado - 通过 websockets 同时收听多个客户端 [英] Tornado - Listen to multiple clients simultaneously over websockets

查看:65
本文介绍了Tornado - 通过 websockets 同时收听多个客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Tornado 在 Python 中创建一个 websocket 服务器.这是 API:http://tornado.readthedocs.org/en/latest/websocket.html

I want to use Tornado for creating a websocket server in Python. Here is the API: http://tornado.readthedocs.org/en/latest/websocket.html

在 API 中,我没有看到获取客户端句柄的选项.如何同时处理多个客户端连接?
例如,on_message(self, message) 方法直接给出消息.不包含已连接客户端的任何句柄.
我想接收客户端请求,做一些处理(这可能需要很长时间),然后回复给客户端.我正在寻找一个可以在以后回复的客户端句柄.

In the APIs, I do not see an option to get a handle for the client. How do I handle multiple client connections at the same time?
For example, on_message(self, message) method directly gives the 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)

每个 websocket 连接都有自己的子类 WebSocketHandler 对象.

Every websocket connection has its own object from your subclassed 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)

这篇关于Tornado - 通过 websockets 同时收听多个客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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