Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tornado websocket handler , self.close() is closing connection without triggering the on_close() method

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 ...
like image 324
Eloy Avatar asked Jan 14 '14 18:01

Eloy


1 Answers

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.

like image 76
A. Jesse Jiryu Davis Avatar answered Oct 17 '22 01:10

A. Jesse Jiryu Davis