I’m using node.js and socket.io. I’m using http-proxy to use port 80 on a machine that’s running apache also. Apache is on a different IP. This all works great.
I added in Cluster and things got funky. It spawns two workers (dual core VM) as expected. But the connection on the client side, is off. Sometimes it’s good, then if you disconnect, there’s a delay reconnecting (there wasn’t without the Cluster).
Here’s the code I have.. any ideas why there’s the delay between disconnect and connect using the cluster?
var http = require('http'),
httpProxy = require('http-proxy'),
io = require('socket.io'),
cluster = require('cluster'),
express = require('express'),
RedisStore = require('connect-redis')(express);
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
//Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died');
});
} else {
//Server for workers
var app = express.createServer().listen(8585, '172.16.183.129');
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: "secret", store: new RedisStore}));
app.use(app.router);
app.use(express.errorHandler({showStack: false, dumpExceptions: false}));
app.use(express.static(__dirname + '/public'));
});
//Create proxy server to use port 80
var proxy = httpProxy.createServer(8585, '172.16.183.129');
proxy.listen(80, '172.16.183.129');
//Initilize socket.io
var io = require('socket.io').listen(app, {origins: '*:*'});
io.sockets.on('connection', function(socket){
var test = setInterval(function() {
socket.emit('test', { result: numCPUs});
i++;
}, 900);
socket.on('disconnect', function () {
console.log('disconnect');
clearInterval(auctionTimer);
});
});
}
You need to add in a RedisStore so that the socket workers can work together. Note that the latest version of socket.io has a built in RedisStore that you probably should use instead of the connect-redis stuff.