2014-02-21 76 views
2

我想保持跟蹤多個websocket連接我必須將WebSocket處理程序對象存儲在列表中。但是我有多個處理程序 - 每個WS URI(端點)都有一個處理程序。可以說我的項目有三個端點 - A,B,C保存龍捲風中的websocket連接列表

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 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' 

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() 

所以我在哪裏創建這個列表,並確保其可見創建的所有對象?我也是python的新手,所以在我的頭上纏一點麻煩。

我也意識到我可能只使用一個URI(端點)並將多個命令作爲消息本身的一部分發送。但是,我不想將WebSocket轉換爲二進制協議。鑑於我們有URI,我應該使用它們。

感謝您的任何幫助。

+0

@羅德海德 - 如果你看到這不是一個WebSocket問題。它更多的是一個python問題。我已經知道如何處理連接,只是不知道如何把它放在python中。所以我不同意它的一個dup(標題可能接近) – user220201

回答

1

這取決於你想要做處理程序是什麼,但是你可以很容易使他們在三個列表訪問:

# 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

+0

非常感謝!我現在意識到的主要問題是使用列表。由於他們允許重複我需要代碼來檢查每個操作的重複,這是我可以看到添加的位置。 set()解決了這個問題,涵蓋了我需要的一切。謝謝! – user220201