简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM