Skip to content

Instantly share code, notes, and snippets.

@dlo
Created May 4, 2010 22:44
Show Gist options
  • Select an option

  • Save dlo/390142 to your computer and use it in GitHub Desktop.

Select an option

Save dlo/390142 to your computer and use it in GitHub Desktop.
Websockets w/ Tornado
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado import websocket
import os
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
self.receive_message(self.on_message)
def on_message(self, message):
self.write_message(message)
settings = {
"static_path": os.path.join(os.path.dirname(__file__))
}
application = tornado.web.Application([
(r"/", EchoWebSocket),
], **settings)
if __name__ == "__main__":
print "Listening on http://localhost:8888/"
server = tornado.httpserver.HTTPServer(application)
server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd"
xml:lang="en">
<head>
<script type='text/javascript' lang='javascript'>
var ws = new WebSocket('ws://localhost:8888');
ws.onopen = function () {
ws.send("Hello, world");
ws.send("Second message");
};
ws.onmessage = function(evt) {
alert(evt.data);
};
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment