WebSocket Handler on_close 方法异步实现 tornado
WebSocket Handler on_close method async Implementation tornado
我正在使用 tornado 版本 6.0.2 构建 Web 应用程序。我正在使用 WebSocket 处理程序来建立与客户端的连接。
示例服务器端实现:
from tornado import websocket
import connectionhandler
class WebSocketHandler(websocket.WebSocketHandler):
def initialize(self, connectionhandler):
self.connectionhandler = connectionhandler
async def open(self):
print("WebSocket opened.")
await self.connectionhandler.connection_established_websocket()
async def on_close(self):
print("WebSocket closed.")
await self.connectionhandler.connection_closed_websocket()
示例客户端实现:
ws = websocket.create_connection("ws://localhost:80/ws?")
ws.close()
当客户端建立连接时,它会调用 open 方法,一切正常。
但是当客户端关闭连接时,我收到错误 on_close was never awaited.
当我删除本机协程时 on_close 方法正在运行。
问题:
如何为 on_close 方法添加本机协程或从 on_close() 调用异步方法?
on_close
并不意味着是一个异步函数。要 运行 来自 on_close
的异步函数,请使用 IOLoop.add_callback
.
from tornado.ioloop import IOLoop
def on_close(self):
IOLoop.current().add_callback(
self.connectionhandler.connection_closed_websocket
)
我正在使用 tornado 版本 6.0.2 构建 Web 应用程序。我正在使用 WebSocket 处理程序来建立与客户端的连接。
示例服务器端实现:
from tornado import websocket
import connectionhandler
class WebSocketHandler(websocket.WebSocketHandler):
def initialize(self, connectionhandler):
self.connectionhandler = connectionhandler
async def open(self):
print("WebSocket opened.")
await self.connectionhandler.connection_established_websocket()
async def on_close(self):
print("WebSocket closed.")
await self.connectionhandler.connection_closed_websocket()
示例客户端实现:
ws = websocket.create_connection("ws://localhost:80/ws?")
ws.close()
当客户端建立连接时,它会调用 open 方法,一切正常。
但是当客户端关闭连接时,我收到错误 on_close was never awaited.
当我删除本机协程时 on_close 方法正在运行。
问题:
如何为 on_close 方法添加本机协程或从 on_close() 调用异步方法?
on_close
并不意味着是一个异步函数。要 运行 来自 on_close
的异步函数,请使用 IOLoop.add_callback
.
from tornado.ioloop import IOLoop
def on_close(self):
IOLoop.current().add_callback(
self.connectionhandler.connection_closed_websocket
)