Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a parent process send socket/server object to child process in Node.js?

Tags:

node.js

Consider:

// Parent

var child = require('child_process').fork('child.js');

// Open up the server object and send the handle.
var server = require('net').createServer();
server.on('connection', function (socket) {
  socket.end('handled by parent');
});
server.listen(1337, function() {
  child.send('server', server);
});

//Child
process.on('message', function(m, server) {
  if (m === 'server') {
    server.on('connection', function (socket) {
      socket.end('handled by child');
    });
  }
});

As shown in above example, parents sends server object to child processes so that even a child had handle some of client connection requests.

How is it achieved in Node.js?

like image 869
Ashish Avatar asked Nov 28 '12 11:11

Ashish


2 Answers

Here is what node does when process.send is called with a handle argument.

And after reading that, the handleConversion function is also interesting to read.

I don't fully understand it yet, but I think essentially the state of the socket/server is serialized and passed between master/worker using IPC. Maybe the state being passed around is enough for each process to bind itself to the socket? Or maybe the parent is keeping a registry of children who can handle any given socket, so once a new connection comes in for some socket, it is sent to a child that registered for it. That part I am less sure about.

like image 114
sandinmyjoints Avatar answered Sep 20 '22 22:09

sandinmyjoints


This is now possible, but only if you're using the net module, which you are.

child.send('socket', socket); Use the second parameter to send:

And to receive from child process:

process.on('message', function(m, socket) {
   if (m === 'socket') {
       console.log(socket); // Net socket object here
   }
});
like image 21
NiCk Newman Avatar answered Sep 18 '22 22:09

NiCk Newman