Skip to content

Instantly share code, notes, and snippets.

@aj0strow
Created February 5, 2014 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aj0strow/8820581 to your computer and use it in GitHub Desktop.
Save aj0strow/8820581 to your computer and use it in GitHub Desktop.
redis & socket.io
modules = [ 'then-redis', 'http', 'express', 'socket.io' ]
[ redis, http, express, io ] = (require(mod) for mod in modules)
# redis
db = redis.createClient()
db.setnx('users:count', 0)
# server
app = express()
index = (req, res) ->
res.sendfile(__dirname + '/index.html')
app.get('/', index)
server = http.createServer(app)
server.listen(process.env.PORT)
# pubsub
sockets = io.listen(server).sockets
key = 'users:count'
onconnect = (socket) ->
publish = db.publish.bind(db, key)
db.incr(key).then(publish)
socket.on('disconnect', -> db.decr(key).then(publish))
sockets.on('connection', onconnect)
client = redis.createClient()
client.on('message', sockets.emit.bind(sockets))
client.subscribe(key)
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('users:count', function (data) {
console.log(data);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment