Skip to content

Instantly share code, notes, and snippets.

@5c077yP
Created November 22, 2014 07:53
Show Gist options
  • Save 5c077yP/2d70f98632afacee6b9b to your computer and use it in GitHub Desktop.
Save 5c077yP/2d70f98632afacee6b9b to your computer and use it in GitHub Desktop.
Simple NodeJS TCP Load Balancer
/* jslint node: true, ass: false, plusplus: true, sloppy: true, indent: 2
*
* A Simple TCP (Round Robin) Load Balancer.
*/
var net = require('net');
var port = 2333; // Listen port
var hosts = [
{ host: '127.0.0.1', port: 2033 },
{ host: '127.0.0.1', port: 2133 }
];
var rrc = 0; // the round robin counter
var getNextHost = function () {
rrc = ++rrc % hosts.length;
return hosts[rrc];
};
var server = net.createServer(function (con) { // connection listener
var connectOptions, client = null;
con.on('data', function (data) {
connectOptions = getNextHost();
console.log('Sending data to:', connectOptions);
client = net.connect(connectOptions, function () { // connect listener
client.end(data); // send data and close the connection
});
});
});
console.log("Binding to port:", port);
server.listen(port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment