Skip to content

Instantly share code, notes, and snippets.

@sat0b
Created June 3, 2017 10:16
Show Gist options
  • Select an option

  • Save sat0b/88b6909e497be7aa518a9df1091f994d to your computer and use it in GitHub Desktop.

Select an option

Save sat0b/88b6909e497be7aa518a9df1091f994d to your computer and use it in GitHub Desktop.
simple websocket
<!DOCTYPE html>
<html>
<head>
<title>simple websocket</title>
</head>
<body>
simple websocket
<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) {
console.log("message : " + event.data);
};
ws.onclose = function(event) {
console.log("closed");
};
});
</script>
</body>
</html>
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
class SocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
print("opened")
def on_message(self, message):
self.write_message(u"this is from python")
def on_close(self):
print("closed")
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