python - 带有 Tornado 的 Websockets : Get access from the "outside" to send messages to clients

标签 python websocket webserver tornado

我开始使用 WebSockets 作为将数据从服务器推送到连接的客户端的方法。由于我使用 python 来编写任何类型的逻辑,所以到目前为止我一直在研究 Tornado。下面的代码片段显示了可以在 Web 上随处找到的最基本的示例:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hello World")

    def on_message(self, message):
        print 'message received %s' % message
        self.write_message('ECHO: ' + message)

    def on_close(self):
    print 'connection closed'


application = tornado.web.Application([
  (r'/ws', WSHandler),
])


if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

实际上,这是按预期工作的。但是,我无法理解如何将其“集成”到我的应用程序的其余部分中。在上面的示例中,WebSocket 仅向客户端发送一些内容作为对客户端消息的回复。如何从“外部”访问 WebSocket?例如,通知所有当前连接的客户端某种事件已经发生——并且这个事件不是来自客户端的任何类型的消息。理想情况下,我想在我的代码中的某处编写如下内容:

websocket_server.send_to_all_clients("Good news everyone...")

我该怎么做?或者我是否完全误解了 WebSockets(或 Tornado)应该如何工作。谢谢!

最佳答案

您需要跟踪所有连接的客户端。所以:

clients = []

def send_to_all_clients(message):
    for client in clients:
        client.write_message(message)

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        send_to_all_clients("new client")
        clients.append(self)

    def on_close(self):
        clients.remove(self)
        send_to_all_clients("removing client")

    def on_message(self, message):
        for client in clients:
            if client != self:
                client.write_message('ECHO: ' + message)

关于python - 带有 Tornado 的 Websockets : Get access from the "outside" to send messages to clients,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562465/

相关文章:

python - 打破无限循环的正确 Python 异常(不应该是无限的)

Java WebSocket 消息限制

python - 在 pyspark 中注册我的 udf 有什么好处吗?

python - 在分配唯一变量时读取多行的最 Pythonic 方式是什么?

c++ - 确保使用 qRegisterMetaType() 注册了 'QAbstractSocket::SocketState'

ruby-on-rails - 线程在Web应用程序中如何工作?

Java - Spring Boot - 无法在端口 8080 上启动 Web 服务器

ruby - 多处理器/多线程Ruby Web服务器如何工作?

Python:为什么一些 Queue.queue 的方法是 "unreliable"?

python-3.x - 用于 WebSocket 通信的 Jupyter