Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Last active October 16, 2016 18:20
Show Gist options
  • Save pulkitsinghal/2b3acd6885278cfb160d7db01729d5e8 to your computer and use it in GitHub Desktop.
Save pulkitsinghal/2b3acd6885278cfb160d7db01729d5e8 to your computer and use it in GitHub Desktop.
Worker > Redis > Notifier Service (multiple nodes) > Browser
// starting point was: https://github.com/mminer/blog-code/blob/master/pattern-for-async-task-queue-results/notifier.js
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
bodyParser = require('body-parser');
// After scaling up, multiple servers can only work with sockets connected to them.
// The socket.io-redis package can solve this by making redis the datastore instead of memory.
var redis = require('socket.io-redis');
//io.adapter(redis({ host: '127.0.0.1', port: 6379 }));
io.adapter(redis({ host: 'redis', port: 6379 }));
// Echo the client's ID back to them when they connect.
io.on('connection', function(socket) {
console.log('connection:', socket.id);
socket.emit('register', socket.id);
});
app.use(express.static('public'));
app.use(express.static('node_modules/socket.io/node_modules/socket.io-client'));
/*app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});*/
// Accept URL-encoded body in POST request.
app.use(bodyParser.urlencoded({ extended: true }));
// Forward task results to the clients who initiated them.
app.post('/notify', function(request, response) {
console.log('request.body:', request.body);
console.log('send notification to:', request.body.clientid);
var client = io.sockets.connected[request.body.clientid];
client.emit('notify', request.body.result);
response.type('text/plain');
response.send('Result broadcast to client.' + Date.now());
});
server.listen(3000, function(){
console.log("Express app started");
});
@pulkitsinghal
Copy link
Author

  1. Need to setup a docker-compose env with one instance of redis and two instances of notifier service behind one nginx
  2. Test that io.sockets.connected[request.body.clientid] works, despite whichever notifier service instance the browsers are connected to

@pulkitsinghal
Copy link
Author

pulkitsinghal commented Oct 14, 2016

Syntax like io.sockets.adapter.rooms[roomId].sockets makes me think that io.sockets.connected[socketId] wont' just work when we test.

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