Created
November 22, 2014 07:53
-
-
Save 5c077yP/2d70f98632afacee6b9b to your computer and use it in GitHub Desktop.
Simple NodeJS TCP Load Balancer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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