问题描述
我是 (python, stackoverflow, tornado) 的新手,所以请耐心等待 :).纠正我.
im new at (python, stackoverflow, tornado) , so please, be patient :). Correct me.
我正在实时应用程序上使用 Tornado.当我在 Websocket 处理程序类中调用 self.close() 时,没有启动 on_close 方法,这次我做了一个小包装,解决了问题并(例如)丢弃了连接的代理(纯 avascript wss api 客户端)正确.
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.
所有网络问题都被丢弃了,因为我糟糕的包装器运行良好,而且我在 LAN 环境中.
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.
谢谢你,真的.
## 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 ...
推荐答案
self.on_close
当且仅当客户端关闭它的 websocket 连接端时才会执行.试试看:如果您打开包含连接到您的服务器的 Javascript 客户端的网页,然后关闭该页面,on_close
将运行.如果您在服务器代码中调用 self.close
,on_close
不应运行.
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.
您的包装器是您问题的合理解决方案;也就是说,这是一种合理的方式,可以确保在您调用 self.close
或客户端断开连接时运行相同的代码.
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.
这篇关于Tornado websocket 处理程序,self.close() 正在关闭连接而不触发 on_close() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!