Skip to content

Instantly share code, notes, and snippets.

Created August 17, 2010 21:12
  • Star 26 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
This is a simple example of WebSocket + Tornado + Redis Pub/Sub usage.
Do not forget to replace YOURSERVER by the correct value.
Keep in mind that you need the *very latest* version of your web browser.
You also need to add Jacob Kristhammar's websocket implementation to Tornado:
Grab it here:
Or clone my fork of Tornado with websocket included:
Oh and the Pub/Sub protocol is only available in Redis 2.0.0:
Tested with Chrome 6.0.490.1 dev under OS X.
For questions / feedback / coffee -> @kizlum or
Have fun.
import threading
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import redis
# This is ugly but I did not want to create multiple files for a so trivial
# example.
<title>Sample test</title>
<script type="text/javascript" src=""></script>
<h1>Hello world</h1>
<form method='POST' action='./'>
<textarea name='data' id="data"></textarea>
<div><input type='submit'></div>
<div id="log"></div>
<script type="text/javascript" charset="utf-8">
var value = $('#data').val();
$.post("./", { data: value }, function(data){
return false;
if ("WebSocket" in window) {
var ws = new WebSocket("ws://YOURSERVER:8888/realtime/");
ws.onopen = function() {};
ws.onmessage = function (evt) {
var received_msg =;
var html = $("#log").html();
html += "<p>"+received_msg+"</p>";
ws.onclose = function() {};
} else {
alert("WebSocket not supported");
def redis_listener():
r = redis.Redis(host='YOURSERVER', db=2)
for message in r.listen():
for element in LISTENERS:
class NewMsgHandler(tornado.web.RequestHandler):
def get(self):
def post(self):
data = self.request.arguments['data'][0]
r = redis.Redis(host='YOURSERVER', db=2)
r.publish('test_realtime', data)
class RealtimeHandler(tornado.websocket.WebSocketHandler):
def open(self):
def on_message(self, message):
def on_close(self):
settings = {
'auto_reload': True,
application = tornado.web.Application([
(r'/', NewMsgHandler),
(r'/realtime/', RealtimeHandler),
], **settings)
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
Copy link

Thank you so much! Exactly what I was looking for....

Copy link

peterbe commented Oct 31, 2011

I love the simplicity of it. Only problem is that it doesn't kill the thread on Ctrl-C on the command line.

Copy link

lbolla commented Feb 11, 2013

I've forked this gist and fixed some issues:

Copy link

New way of Tornado + Websocket + Simple EE;;

Copy link

so cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment