1

The idea is to create server in master process, and handle requests in workers. I want to utilize all CPU cores and to have kinda load balance as well.

At first I tried to send server handler from master to worker:

var cluster = require('cluster');

if (cluster.isMaster) {
    var app = require('express').createServer();
    app.listen(1234);

    var worker = cluster.fork();
    worker.stdin.write('fd', 'utf8', app._handle);
} else {
    process.stdin.resume();
    process.stdin.on('fd', function(fd){
        var stream = require('net').Stream(fd);
        var io = require('socket.io').listen(stream);
        io.sockets.on('connection', function(socket){
            ...
        }
    }
}

but write did not fired on('fd'...) event handler in worker. Then I put everything to master in order to check if this is possible at all:

    var app = require('express').createServer();
    app.listen(1234);
    var stream = require('net').Stream(app._handler);
    var io = require('socket.io').listen(stream);

the server starts without any errors but does not work. I cant event request the socket.io.js script from the client side with tag:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>
Response: Cannot GET /socket.io/socket.io.js

So I have two troubles:

  1. How to send opened socket descriptor to the worker?
  2. How to set up handler for the server by this descriptor?
htonus
  • 629
  • 1
  • 9
  • 19

1 Answers1

0

You don't need to take care of file descriptors etc on your own, look at a similar question I've just answered here:

Node.js, multi-threading and Socket.io

Code sample:

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  var sio = require('socket.io')
  , RedisStore = sio.RedisStore
  , io = sio.listen(8080, options);

  // Somehow pass this information to the workers
  io.set('store', new RedisStore);

  // Do the work here
  io.sockets.on('connection', function (socket) {
    socket.on('chat', function (data) {
      socket.broadcast.emit('chat', data);
    })
  });
}
Community
  • 1
  • 1
alessioalex
  • 62,577
  • 16
  • 155
  • 122
  • It looks like script will create a number of sockets in workers and bind them to one port. I expect an exception here. Could you please explain what's going on here? – htonus Dec 20 '11 at 07:25
  • Checkout the documentation for cluster here to understand better: http://nodejs.org/docs/v0.6.6/api/cluster.html It has some examples, similar to my one above. – alessioalex Dec 20 '11 at 07:32