I am implementing a WebSockets server in Tornado 3.2. The client connecting to the server will not be a browser.
In cases where there is feedback between the server and the client, I would like to add max. the time when the server will wait for the client to respond before closing the connection.
This is roughly what I tried:
import datetime import tornado class WSHandler(WebSocketHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.timeout = None def _close_on_timeout(self): if self.ws_connection: self.close() def open(self): initialize() def on_message(self, message):
I am klutz and is there a much easier way to do this? I can't even schedule a simple print statement through add_timeout above.
I also need help with testing. This is what I have so far:
from tornado.websocket import websocket_connect from tornado.testing import AsyncHTTPTestCase, gen_test import time class WSTests(AsyncHTTPTestCase): @gen_test def test_long_response(self): ws = yield websocket_connect('ws://address', io_loop=self.io_loop)
The client has no problems with writing and reading from the socket. This is probably due to the fact that add_timeout does not start.
Is a test required to somehow allow the execution of a timeout callback on the server? I would not have thought, as the docs say the tests run in their own IOLoop.
Edit
This is a working version with Ben's suggestions.
import datetime import tornado class WSHandler(WebSocketHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.timeout = None def _close_on_timeout(self): if self.ws_connection: self.close() def open(self): initialize() def on_message(self, message):
Test:
from tornado.websocket import websocket_connect from tornado.testing import AsyncHTTPTestCase, gen_test import time class WSTests(AsyncHTTPTestCase): @gen_test def test_long_response(self): ws = yield websocket_connect('ws://address', io_loop=self.io_loop)