在Tornado中保持WebSocket连接列表

4

我认为为了跟踪多个WebSocket连接,我需要在列表中存储WebSocket处理器对象。但是,我有多个处理器 - 每个WS URI(端点)一个。假设我的项目有三个端点 - A,B,C。

ws://www.example.com/A
ws://www.example.com/B
ws://www.example.com/C

因此,为了处理每个连接,我有三个处理程序。所以,我困惑于在哪里创建列表来存储处理对象以供稍后使用。

添加列表之前的代码如下--

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

    def on_message(self, message):
        print 'message received %s' % message

    def on_close(self):
        print 'connection closed'


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

    def on_message(self, message):
        print 'message received %s' % message

    def on_close(self):
        print 'connection closed'

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

    def on_message(self, message):
        print 'message received %s' % message

    def on_close(self):
        print 'connection closed'

application = tornado.web.Application([
    (r'/A', WSHandlerA),
    (r'/B', WSHandlerB),
    (r'/C', WSHandlerC),
])


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

那么我应该在哪里创建这个列表,并确保它对所有创建的对象可见?我也是新手,所以有点难以理解。

我还意识到我可能只需要一个URI(终端点),并将多个命令作为消息的一部分发送。但是,我不想将WebSocket转换为二进制协议。鉴于我们有URI,我应该使用它们。

感谢任何帮助。


@Rod Hyde - 这不是一个Websocket问题,如果你看到的话。这更像是一个Python问题。我已经知道如何处理连接,只是不知道如何在Python中实现。所以我不同意它是一个重复的问题(标题可能相似)。 - user220201
1个回答

3

这取决于您想要使用处理程序来做什么,但是您可以轻松地将它们分别放入三个列表中:

# Global variables.
a_handlers = []
b_handlers = []
c_handlers = []

WSHandlerA.open()会执行a_handlers.append(self),而WSHandlerB.open()会执行b_handlers.append(self),以此类推。WSHandlerA.on_close()会执行a_handlers.remove(self)

如果您想对所有A处理程序执行某些操作:

for handler in a_handlers:
    handler.write_message("message on A")

处理所有处理程序的方法:

for handler in a_handlers + b_handlers + c_handlers:
    # do something....
    pass

顺便说一下,如果您在每组处理程序中使用Python set()而不是列表,它会更好一些。使用集合而不是列表,使用adddiscard而不是appendremove


非常感谢!我现在意识到我的主要问题是与列表的使用有关。由于它们允许重复,所以我需要编写代码来检查每个操作中是否有重复项,这就是我可以看到需要添加的地方。set() 解决了这个问题并涵盖了我需要的所有内容。谢谢! - user220201
Short and simple. Thank you! - tonymontana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接