tornado.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import asyncio
  2. import json
  3. import tornado
  4. import tornado.websocket
  5. from tornado.web import StaticFileHandler
  6. from . import STATIC_PATH
  7. from ..session import AsyncBasedSession, ThreadBasedWebIOSession, get_session_implement
  8. from ..utils import get_free_port
  9. def webio_handler(task_func, debug=True):
  10. class WSHandler(tornado.websocket.WebSocketHandler):
  11. def check_origin(self, origin):
  12. return True
  13. def get_compression_options(self):
  14. # Non-None enables compression with default options.
  15. return {}
  16. def send_msg_to_client(self, controller: AsyncBasedSession):
  17. for msg in controller.get_task_messages():
  18. self.write_message(json.dumps(msg))
  19. def open(self):
  20. print("WebSocket opened")
  21. self.set_nodelay(True)
  22. self._close_from_session = False # 是否从session中关闭连接
  23. if get_session_implement() is AsyncBasedSession:
  24. self.controller = AsyncBasedSession(task_func, on_task_message=self.send_msg_to_client,
  25. on_session_close=self.close)
  26. else:
  27. self.controller = ThreadBasedWebIOSession(task_func, on_task_message=self.send_msg_to_client,
  28. on_session_close=self.close_from_session,
  29. loop=asyncio.get_event_loop())
  30. print('open return, ThreadBasedWebIOSession.thread2session', ThreadBasedWebIOSession.thread2session)
  31. def on_message(self, message):
  32. # print('on_message', message)
  33. data = json.loads(message)
  34. self.controller.send_client_event(data)
  35. def close_from_session(self):
  36. self._close_from_session = True
  37. self.close()
  38. def on_close(self):
  39. if not self._close_from_session:
  40. self.controller.close(no_session_close_callback=True)
  41. print("WebSocket closed")
  42. return WSHandler
  43. def start_server(target, port=0, host='', debug=True,
  44. websocket_max_message_size=None,
  45. websocket_ping_interval=None,
  46. websocket_ping_timeout=None,
  47. **tornado_app_settings):
  48. """Start a Tornado server to serve `target` function
  49. :param target: task function. It's a coroutine function is use AsyncBasedSession or
  50. a simple function is use ThreadBasedWebIOSession.
  51. :param port: server bind port. set ``0`` to find a free port number to use
  52. :param host: server bind host. ``host`` may be either an IP address or hostname. If it's a hostname,
  53. the server will listen on all IP addresses associated with the name.
  54. set empty string or to listen on all available interfaces.
  55. :param debug: Tornado debug mode
  56. :param int websocket_max_message_size: Max bytes of a message which Tornado can accept.
  57. Messages larger than the ``websocket_max_message_size`` (default 10MiB) will not be accepted.
  58. :param int websocket_ping_interval: If set to a number, all websockets will be pinged every n seconds.
  59. This can help keep the connection alive through certain proxy servers which close idle connections,
  60. and it can detect if the websocket has failed without being properly closed.
  61. :param int websocket_ping_timeout: If the ping interval is set, and the server doesn’t receive a ‘pong’
  62. in this many seconds, it will close the websocket. The default is three times the ping interval,
  63. with a minimum of 30 seconds. Ignored if ``websocket_ping_interval`` is not set.
  64. :param tornado_app_settings: Additional keyword arguments passed to the constructor of ``tornado.web.Application``.
  65. ref: https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings
  66. :return:
  67. """
  68. kwargs = locals()
  69. app_options = ['debug', 'websocket_max_message_size', 'websocket_ping_interval', 'websocket_ping_timeout']
  70. for opt in app_options:
  71. if opt is not None:
  72. tornado_app_settings[opt] = kwargs[opt]
  73. if port == 0:
  74. port = get_free_port()
  75. handlers = [(r"/io", webio_handler(target)),
  76. (r"/(.*)", StaticFileHandler, {"path": STATIC_PATH, 'default_filename': 'index.html'})]
  77. app = tornado.web.Application(handlers=handlers, **tornado_app_settings)
  78. http_server = tornado.httpserver.HTTPServer(app)
  79. http_server.listen(port, address=host)
  80. print('Listen on %s:%s' % (host or '0.0.0.0', port))
  81. tornado.ioloop.IOLoop.instance().start()