Search code examples
pythonwebsockettornado

How to make two Python Tornado websocket channels available at different URLs


I have two queues that should be subscribed to separately when opening a websocket connection to either endpoint. One should be ws://127.0.0.1:8000/channel_one and the other is ws://127.0.0.1:8000/channel_two.

How do I implement this URL structure in Python Tornado and make it so there are two endpoints in the same program?


Solution

  • Adapting the sample hello world app:

    import tornado.web
    import tornado.websocket
    
    class HandlerOne(websocket.WebSocketHandler):
        pass
    
    class HandlerTwo(websocket.WebSocketHandler):
        pass
    
    def make_app():
        return tornado.web.Application([
            (r"/channel_one", HandlerOne),
            (r"/channel_two", HandlerTwo),
        ])
    
    if __name__ == "__main__":
        app = make_app()
        app.listen(8000)
        tornado.ioloop.IOLoop.current().start()