Tornado websocket处理程序self.close()正在关闭连接,而不会触发on-close()方法

2024-04-28 08:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的(Python,stackoverflow,tornado),所以请耐心点。纠正我。

我在一个实时应用程序上和tornado一起工作。当我在Websocket处理程序类中调用self.close()时,不会触发on_close方法,这一次我做了一个小包装,修复了问题,并(例如)正确地丢弃了连接的代理(纯avascript wss api客户端)。

所有的网络问题都被丢弃了,因为我糟糕的包装器工作得很好,而且im是在LAN环境中。

有人有同样的问题吗?没有解释我睡不着。

谢谢,真的。

## 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 ...

Tags: theselfjsonmessagecloserawison
2条回答

self.on_close在且仅当客户端关闭其websocket连接时执行。尝试一下:如果打开的网页包含连接到服务器的Javascript客户端,则关闭该网页,on_close将运行。^如果在服务器代码中调用self.close,则{}不应运行。

包装器是解决问题的合理方法;也就是说,它是确保在调用self.close或客户端断开连接时运行相同代码的合理方法。

如前所述,on_close()只在客户端关闭连接时执行,因此它是清理资源的好地方。

对于任何清理,请使用这里记录的on_finish()方法https://tornado.readthedocs.org/en/latest/web.html#tornado.web.RequestHandler.on_finish

相关问题 更多 >