From 90b877a2c785bb7691249d31e23138e0385001ae Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Sun, 30 Oct 2016 16:07:10 +0800 Subject: webui: Build the Web UI using Tornado with WebSocket Tornado: http://www.tornadoweb.org/ --- fg21sim/webui/__init__.py | 4 ++++ fg21sim/webui/app.py | 37 +++++++++++++++++++++++++++++++++++++ fg21sim/webui/websocket.py | 27 +++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 fg21sim/webui/__init__.py create mode 100644 fg21sim/webui/app.py create mode 100644 fg21sim/webui/websocket.py (limited to 'fg21sim') diff --git a/fg21sim/webui/__init__.py b/fg21sim/webui/__init__.py new file mode 100644 index 0000000..637e653 --- /dev/null +++ b/fg21sim/webui/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2016 Weitian LI +# MIT license + +from .app import make_application diff --git a/fg21sim/webui/app.py b/fg21sim/webui/app.py new file mode 100644 index 0000000..63d80be --- /dev/null +++ b/fg21sim/webui/app.py @@ -0,0 +1,37 @@ +# Copyright (c) 2016 Weitian LI +# MIT license + +""" +Web user interface (UI) of "fg21sim" based upon Tornado_. + +.. _Tornado: http://www.tornadoweb.org/ +""" + +import os + +import tornado.web + +from .websocket import EchoWSHandler + + +class IndexHandler(tornado.web.RequestHandler): + def get(self): + self.render("index.html") + + +_settings = { + # The static files will be served from the default "/static/" URI + "static_path": os.path.join(os.path.dirname(__file__), "static"), + "template_path": os.path.join(os.path.dirname(__file__), "templates"), +} + + +def make_application(**kwargs): + settings = _settings + settings.update(kwargs) + appplication = tornado.web.Application( + handlers=[ + (r"/", IndexHandler), + (r"/ws", EchoWSHandler), + ], **settings) + return appplication diff --git a/fg21sim/webui/websocket.py b/fg21sim/webui/websocket.py new file mode 100644 index 0000000..ab846df --- /dev/null +++ b/fg21sim/webui/websocket.py @@ -0,0 +1,27 @@ +# Copyright (c) 2016 Weitian LI +# MIT license + +""" +Communicate with the "fg21sim" simulation program through the Web UI using +the WebSocket_ technique, which provides full-duplex communication channels +over a single TCP connection. + +.. _WebSocket: https://en.wikipedia.org/wiki/WebSocket , + http://caniuse.com/#feat=websockets +""" + +import tornado.websocket + + +class EchoWSHandler(tornado.websocket.WebSocketHandler): + def open(self): + print("WebSocket opened") + + def on_message(self, message): + print("Message received: %s" % message) + msg_back = message[::-1] + print("Message sent back: %s" % msg_back) + self.write_message(msg_back) + + def on_close(self): + print("WebSocket closed") -- cgit v1.2.2