Created
February 5, 2014 10:11
-
-
Save aj0strow/8820581 to your computer and use it in GitHub Desktop.
redis & socket.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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