问题
im new at (python, stackoverflow, tornado) , so please, be patient :). Correct me.
Im working with tornado on a real-time app. When i call self.close() inside the Websocket handler class , the on_close method is not fired up , for this time i did a little wrapper , fixing the problem and (for example) discarding that connected agent (pure avascript wss api client) correctly.
All network problems are discarded , since my poor wrapper is working nicely and im in a LAN enviroment.
is someone having the same problem ? I cant sleep without an explanation.
THANK YOU , really.
## imports and other stuff 
AGENTS = set()     
class BackofficeWSSRailMain(tornado.websocket.WebSocketHandler):   
     def on_open(self):                  
       pass
     def on_message(self,raw_message):
       json_msg=json.loads(raw_message)
       login = function_that_process_login(json_msg)
       if login == True:
          AGENTS.add(self)
          self.write_message("ok")         
       else:
          self.write_message("nologin")
          self.close()         ### this part should fireup 
                               ### the on_close method but nothing 
                               ### happens so AGENT is not discarded.
                               ### here is when i actually call on_close_wrapper(),
                               ### the method below. 
     def on_close_wrapper(self):
       self.close()            ### this is my actual solution , 
                               ### waiting for more research.
       self.on_close()
     def on_close(self):      
       AGENTS.discard(self)
   ## Calling ioloop ...
    回答1:
self.on_close is executed if and only if the client closes its side of the websocket connection. Try it: If you open a web page that contains a Javascript client which connects to your server, then you close the page, on_close will run. on_close is not supposed to run if you call self.close in your server code.
Your wrapper is a reasonable solution to your problem; that is, it's a reasonable way to ensure that the same code runs either when you call self.close or when the client disconnects.
回答2:
As mentioned, on_close() is only executed if the client closes the connection, so it's a good place to clean up resources.
For any cleanup use the on_finish() method documented here https://tornado.readthedocs.org/en/latest/web.html#tornado.web.RequestHandler.on_finish
来源:https://stackoverflow.com/questions/21121436/tornado-websocket-handler-self-close-is-closing-connection-without-triggerin