Create a gist now

Instantly share code, notes, and snippets.

@mrjoes /INSTALL.txt
Last active May 29, 2016

What would you like to do?
Dead simple broker on top of sockjs-tornado
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script>
$(function() {
var conn = new SockJS('http://localhost:8080/push');
conn.onmessage = function(e) {
console.log('Got', e.data);
}
});
</script>
</body>
</html>
1. pip install -r reqs.pip
2. server.py
3. open client.html in browser
4. redis-cli publish push '123456'
5. check browser console
Tornado>=2.2
sockjs-tornado
toredis
# -*- 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):
logging.info('Incoming client from %s' % info.ip)
self.clients.add(self)
def on_message(self, message):
logging.debug('Received something from client: %s', message)
def on_close(self):
self.clients.remove(self)
@classmethod
def pubsub(cls, data):
msg_type, msg_chan, msg = data
if msg_type == 'message':
logging.debug('Pushing: %s' % msg)
for c in cls.clients:
c.send(msg)
if __name__ == "__main__":
# Logging
import logging
logging.getLogger().setLevel(logging.DEBUG)
# Parse options. TODO: Use decent option parsing library.
parser = argparse.ArgumentParser()
parser.add_argument('--endpoint',
default='/push', dest='endpoint',
help='SockJS URL endpoint')
parser.add_argument('--port',
type=int, default=8080, dest='port',
help='SockJS server port')
parser.add_argument('--key',
default='push', dest='key',
help='Redis key')
parser.add_argument('--redis_server',
default='localhost', dest='redis_server',
help='Redis host')
parser.add_argument('--redis_port',
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)
logging.info('Listening on port %d for redis key %s', v.port, v.key)
tornado.ioloop.IOLoop.instance().start()
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