Skip to content

Instantly share code, notes, and snippets.

@jblashill
Created March 29, 2014 02:31
Show Gist options
  • Save jblashill/9847290 to your computer and use it in GitHub Desktop.
Save jblashill/9847290 to your computer and use it in GitHub Desktop.
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
var subscribers = {};
var publishMessage = function(channel, message) {
var sockets = subscribers[channel];
if (sockets) {
sockets.forEach(function(socket) {
socket.emit('message', message); // 'messsage' is just something arbitrary I decided to call this "event"
});
}
};
var subscribe = function(channel, socket) {
if (!subscribers[channel]) {
subscribers[channel] = [];
}
subscribers[channel].push(socket);
}
app.get('/api/publish/:channel', function (req, res) {
var message = {
type: req.param('type')
};
publishMessage(req.param('channel'), message);
});
io.sockets.on('connection', function (socket) {
socket.on('subscribe', function (channel) {
subscribe(channel, socket);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment