Created
November 19, 2018 07:12
-
-
Save chfw/be5ce3a3ff9122573c6aeaaec0404b60 to your computer and use it in GitHub Desktop.
This file contains 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
from tornado.websocket import WebSocketHandler | |
from tornado.web import Application, RequestHandler | |
from tornado.ioloop import IOLoop | |
HTML = """ | |
<html> | |
<div id="messages"></div> | |
<script> | |
var ws = new WebSocket("ws://localhost:8888/websocket"); | |
ws.onopen = function() { | |
ws.send("Hello, world"); | |
}; | |
ws.onmessage = function (evt) { | |
var the_div = document.getElementById("messages"); | |
the_div.innerHTML = evt.data + "<br>" + the_div.innerHTML; | |
}; | |
</script> | |
</html> | |
""" | |
class MainHandler(RequestHandler): | |
def get(self): | |
self.write(HTML) | |
class EchoWebSocket(WebSocketHandler): | |
clients = [] | |
def open(self): | |
self.clients.append(self) | |
print("WebSocket opened") | |
def on_message(self, message): | |
for client in self.clients: | |
client.write_message("You said:" + message) | |
def on_close(self): | |
print("WebSocket closed") | |
def make_app(): | |
return Application([ | |
(r"/websocket", EchoWebSocket), | |
(r"/", MainHandler), | |
]) | |
if __name__ == "__main__": | |
app = make_app() | |
app.listen(8888) | |
IOLoop.current().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment