Skip to content

Instantly share code, notes, and snippets.

@squaremo
Created May 3, 2012 20:49
Show Gist options
  • Select an option

  • Save squaremo/2589247 to your computer and use it in GitHub Desktop.

Select an option

Save squaremo/2589247 to your computer and use it in GitHub Desktop.
Socket handoff in Node.JS

Same idea as https://gist.github.com/2500291, with node.js. Do

$ node forkpeer.js

It'll print out its pid. Then

$ curl http://localhost:8000/

To reload it, use

$ kill -s HUP <pid>

So, e.g., change the message in the response, sighup, and make another request to see the change.

var http = require('http'),
child_process = require('child_process');
var srv = http.createServer(doReq);
function forkforkfork() {
var child = child_process.fork('./forkpeer', ['--child']);
child.send('go go go', srv._handle);
return child;
}
process.on('SIGHUP', function() {
forkforkfork();
srv.close();
});
if (process.argv.length > 2 && process.argv[2] == '--child') {
process.on('message', function(_, handle) {
srv.listen(handle, function() {
console.log("Process " + process.pid + " listening");
});
});
}
else {
srv.listen(8000, function() {
console.log("Process " + process.pid + " listening on 8000");
});
}
function doReq(_req, res) {
res.writeHead(200);
res.end("Hello from process " + process.pid + "\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment