Search code examples
pythontornado

Can I get IP address and port of disconnected client in Tornado


Currently when my tornado server receives a 'connection opened' event, I store the client's WebSocketHandler in a players dict with its key being and IP/port combo.

players = {}

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        global players
        players[self.get_id()] = self

    def get_id(self):
        ip = self.request.remote_ip
        port = str(self.stream.socket.getpeername()[1])
        return ip + ":" + port

What I'd like to do is remove the player from the dict when its connection closes. Something similar to this:

class WSHandler(tornado.websocket.WebSocketHandler):
    def on_close(self):
        global players
        players.pop(self.get_id(), None)

The port doesn't seem to be accessible so I can't re-create the id that I had set up previously. Is it possible to retrieve the port some other way?


Solution

  • Each connection will create its own instance of WSHandler, so simply store the data on the instance on initialisation:

    def open(self):
        self.id = self.get_id()
        ...