Created
June 3, 2017 11:16
-
-
Save sat0b/37236192b51e2b2e9670b2dc85b5663a to your computer and use it in GitHub Desktop.
digital clock based on websocket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Digital clock</title> | |
| </head> | |
| <body> | |
| <script> | |
| document.addEventListener('DOMContentLoaded', function() { | |
| var ws = new WebSocket("ws://" + location.host + "/ws"); | |
| ws.onopen = function(event) { | |
| console.log("open !"); | |
| ws.send("open"); | |
| }; | |
| ws.onmessage = function(event) { | |
| document.getElementById("msg").innerHTML = event.data; | |
| }; | |
| ws.onclose = function(event) { | |
| console.log("closed"); | |
| }; | |
| }); | |
| </script> | |
| <div style="text-align:center"> | |
| Digital clock | |
| <div id="msg"></div> | |
| </div> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import datetime | |
| import tornado.ioloop | |
| import tornado.web | |
| import tornado.websocket | |
| import tornado.httpserver | |
| import tornado.ioloop | |
| from tornado.ioloop import PeriodicCallback | |
| class IndexHandler(tornado.web.RequestHandler): | |
| def get(self): | |
| self.render("index.html") | |
| class SocketHandler(tornado.websocket.WebSocketHandler): | |
| def open(self): | |
| print("opened") | |
| self.callback = PeriodicCallback(self.send_time, 10) | |
| self.callback.start() | |
| def on_message(self, message): | |
| pass | |
| def send_time(self): | |
| now = str(datetime.datetime.now()) | |
| self.write_message(u"{}".format(now[:-4])) | |
| def on_close(self): | |
| print("closed") | |
| self.callback.stop() | |
| if __name__ == "__main__": | |
| application = tornado.web.Application([ | |
| (r"/", IndexHandler), | |
| (r"/ws", SocketHandler), | |
| ], debug=True) | |
| http_server = tornado.httpserver.HTTPServer(application) | |
| http_server.listen(8888) | |
| tornado.ioloop.IOLoop.current().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment