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

时间:2014-01-14 18:44:12

标签: python web websocket tornado

我是新的(python,stackoverflow,龙卷风),所以请耐心等待:)。纠正我。

我在实时应用上使用龙卷风。当我在Websocket处理程序类中调用self.close()时,on_close方法没有被启动,这次我做了一个小包装,解决了问题并(例如)丢弃了连接代理(纯avascript wss api客户端)正确。

所有的网络问题都被丢弃了,因为我糟糕的包装器工作得非常好,并且处于局域网环境中。

有人遇到同样的问题吗?我无法入睡而没有解释。

谢谢,真的。

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

2 个答案:

答案 0 :(得分:7)

当且仅当客户端关闭websocket连接的一侧时,才执行

self.on_close。试一试:如果你打开一个包含连接到你服务器的Javascript客户端的网页,那么你关闭页面,on_close就会运行。如果您在服务器代码中调用on_close,则不应运行self.close

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

答案 1 :(得分:0)

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

对于任何清理,请使用此处记录的on_finish() <{1}}

方法