Tornado: Identify / track connections of websockets?

Joseph picture Joseph · Jul 27, 2012 · Viewed 14.8k times · Source

I have a basic Tornado websocket test:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

class WSHandler(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'/ws', WSHandler),
])


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

I want to be able to handle multiple connections (which it seems to do already) but also to be able to reference other connections. I don't see a way to identify and keep track of individual connections, just to be able to handle events on connection open, receipt of messages, and connection close.

[Edit]
Thought of creating a dict where the key is the Sec-websocket-key and and the value is the WSHandler object... thoughts? I'm not sure how dependable Sec-websocket-key is to be unique.

Answer

Cole Maclean picture Cole Maclean · Jul 28, 2012

The simplest method is just to keep a list or dict of WSHandler instances:

class WSHandler(tornado.websocket.WebSocketHandler):
    clients = []

    def open(self):
        self.clients.append(self)
        print 'new connection'
        self.write_message("Hello World")

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

    def on_close(self):
        self.clients.remove(self)
        print 'closed connection'

If you want to identify connections, e.g. by user, you'll probably have to send that information over the socket.