【问题标题】:Python WebSocket server that forwards messages from other server转发来自其他服务器的消息的 Python WebSocket 服务器
【发布时间】:2014-08-29 20:05:17
【问题描述】:

我的服务器可以访问通过 TCP 套接字接收实时更新的 API(在广播模式下使用 ZeroMQ)。

我想构建一个网络服务,在网站上向人们显示这些更新。要转发这些更新,通过 WebSockets 与所有客户端保持持续连接似乎是最好的解决方案。

我对如何分别做这些事情有一个很好的想法,但我如何有效地将这两者结合到一个 Python 服务器应用程序中?

我目前在伪代码中的想法是这样的:

while True:
    acceptNewWebSocketConnections()
    update = receiveUpdateZeroMQ()
    sendMessageToAllWebSockets(update)

什么样的 Python 库会支持这种模型,如何在防止拥塞的同时实现它?

【问题讨论】:

    标签: python websocket zeromq


    【解决方案1】:

    作为 mguijarr 所说的替代方案,您可以在 IOLoop 中同时使用 Tornado 和 zmq。

    IOLoop 基本上是检查套接字是否可供读取,以及何时调用给定回调。它在单线程上运行,但由于它几乎不会浪费时间在“等待”上,因此它通常更快!

    在 ZMQ 中使用 tornado 非常简单,因此您所描述的架构可以是这样的:

    from zmq.eventloop import zmqstream, ioloop
    import tornado.web
    from tornado import websocket
    
    class MyBroadcastWebsocket(websocket.WebSocketHandler):
        clients = set()
    
        def open(self):
            self.clients.add(self)
    
        @classmethod
        def broadcast_zmq_message(cls, msg):
            for client in cls.clients:
                client.write_message('Message:' + str(msg)) # Send the message to all connected clients
    
        def on_close(self):
            self.clients.remove(self)
    
    def run():
        ioloop.install()
        my_stream = zmqstream.ZMQStream(my_zmq_socket) # i.e. a pull socket
        my_stream.on_recv(MyBroadcastWebsocket.broadcast_zmq_message) # call this callback whenever there's a message
    
    if __name__ == "__main__":
        application = tornado.web.Application([
            (r"/websocket", MyBroadcastWebsocket),
        ])
        application.listen(8888)
        ioloop.IOLoop.instance()
    

    就是这样! 您可以在zmqtornado 的文档中查看更多信息。

    【讨论】:

    • 谢谢,看起来好多了!
    • 当然。请注意,我犯了一个小错误(覆盖的方法是“on_close”而不是“close”)
    【解决方案2】:

    我建议使用gevent 为所有连接设置一个事件循环, 因为 zmq 的 Python 绑定支持 gevent (import zmq.green as zmq) 而你 这里还有一个 gevent websockets 实现:gevent-websocket;由于 WSGI,gevent 与许多 Web 服务器兼容。

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      相关资源
      最近更新 更多