Skip to content

Instantly share code, notes, and snippets.

Last active February 2, 2018 21:25
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mrjoes/3284402 to your computer and use it in GitHub Desktop.
Save mrjoes/3284402 to your computer and use it in GitHub Desktop.
Dead simple broker on top of sockjs-tornado
<!DOCTYPE html>
<script src=""></script>
<script src=""></script>
$(function() {
var conn = new SockJS('http://localhost:8080/push');
conn.onmessage = function(e) {
1. pip install -r reqs.pip
3. open client.html in browser
4. redis-cli publish push '123456'
5. check browser console
# -*- coding: utf-8 -*-
import sys
import argparse
import tornado.ioloop
import tornado.web
import sockjs.tornado
import toredis
# Our sockjs connection class.
# sockjs-tornado will create new instance for every connected client.
class BrokerConnection(sockjs.tornado.SockJSConnection):
clients = set()
def on_open(self, info):'Incoming client from %s' % info.ip)
def on_message(self, message):
logging.debug('Received something from client: %s', message)
def on_close(self):
def pubsub(cls, data):
msg_type, msg_chan, msg = data
if msg_type == 'message':
logging.debug('Pushing: %s' % msg)
for c in cls.clients:
if __name__ == "__main__":
# Logging
import logging
# Parse options. TODO: Use decent option parsing library.
parser = argparse.ArgumentParser()
default='/push', dest='endpoint',
help='SockJS URL endpoint')
type=int, default=8080, dest='port',
help='SockJS server port')
default='push', dest='key',
help='Redis key')
default='localhost', dest='redis_server',
help='Redis host')
default=6379, dest='redis_port',
help='Redis port')
v = parser.parse_args()
# Initialize tornado-redis and subscribe to key
rclient = toredis.Client()
rclient.connect(v.redis_server, v.redis_port)
rclient.subscribe(v.key, BrokerConnection.pubsub)
# Initialize sockjs-tornado and start IOLoop
BrokerRouter = sockjs.tornado.SockJSRouter(BrokerConnection, v.endpoint)
app = tornado.web.Application(BrokerRouter.urls)
app.listen(v.port)'Listening on port %d for redis key %s', v.port, v.key)
Copy link

mkoutar commented Dec 18, 2014

I want to add some modifications : each time a client is connected he send a key and according to the key the app will subscribe him to the key sended .. I triyed to move the subscribe part to the on_message function but it's not working ..

Any help or hint ?

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