2014-02-21 6 views
2

여러 websocket 연결을 추적하기 위해 생각한 목록에 WebSocket 처리기 개체를 저장해야합니다. 하지만 여러 개의 처리기가 있습니다. 각 WS URI (끝점)마다 하나씩입니다. 내 프로젝트는 세 가지 엔드 포인트가 말할 수 - 그래서 이들 각각에 대한 연결을 처리하는 토네이도에서 websocket 연결 목록 유지하기

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

C

, A, B를, 나는 3 핸들러가 있습니다. 그래서 나중에 사용할 핸들러 객체를 저장할 목록을 만들 위치에 대해 의아해합니다.

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

그래서 나는이 목록을 만들고 않는 경우 생성 된 모든 객체에 볼 수의 확인 - 목록을 추가하기 전에

내 코드는? 나는 파이썬에 익숙하지 않아서 머리를 감싸는 데 어려움을 겪고있다.

나는 또한 단 하나의 URI (끝점) 만 사용하고 메시지 자체의 일부로 여러 명령을 보낼 수 있음을 알고 있습니다. 하지만 WebSocket을 바이너리 프로토콜로 바꾸고 싶지는 않습니다. URI가 있다는 것을 감안할 때 나는 그것을 사용해야 만합니다.

도움 주셔서 감사합니다.

+0

@Rod Hyde - 이것은 웹 소켓 질문과 같이 볼 수 없습니다. 그 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)입니다.

당신이 모든 핸들러와 함께 무언가를 할 경우 당신이 목록 대신 파이썬 set()를 사용하는 경우, 그런데

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

:

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

모든 핸들러 뭔가를 핸들러의 집합마다 조금 더 좋아질 것입니다. 목록 대신 집합을 사용하면 appendremove 대신 adddiscard을 사용하십시오.

+0

고마워! 지금 제가 깨닫고있는 주요 문제는 목록을 사용하는 것입니다. 그들은 중복을 허용하기 때문에 각 작업에 대해 중복을 확인하는 코드가 필요했습니다. 추가 할 위치를 확인할 수 있습니다. set()은 문제를 해결하고 필요한 모든 것을 다룹니다. 감사! – user220201