Search code examples
pythonpython-3.xwebsockettornado

WebSocket Handler on_close method async Implementation tornado


I am working on building a web application using tornado version 6.0.2. I am using WebSocket handler for setting up the connection with the client.

Sample Server-side Implementation:

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()

Sample Client-side Implementation:

ws = websocket.create_connection("ws://localhost:80/ws?")
ws.close()

When the client establishes the connection it calls the open method and everything is working properly.

But When the client closes the connection I get the error on_close was never awaited.

When I remove the native coroutine on_close method is working.

Question :

How can I add the native coroutines for the on_close method or call the asynchronous method from the on_close()?


Solution

  • on_close is not meant to be an async function. To run an async function from on_close, use IOLoop.add_callback.

    from tornado.ioloop import IOLoop
    
    
    def on_close(self):
         IOLoop.current().add_callback(
            self.connectionhandler.connection_closed_websocket
         )