简体   繁体   中英

Redirecting clients from one Node.js server to another Node.js server

I'm creating a socket server like this:

var net = require('net');
net.createServer(function (socket) {
//Run code here, to select where to redirect this client
}).listen(5000);

This would be my master server, where I decide where to redirect a client (eg I want all the clients that are coming from an specific area to connect to an specific server, but I want the master server to decide, because is not just about the geographic area, but some other data to analyse to decide where to redirect the client).

I want somehow to redirect the client to another Node.js server running on the same "localhost" but different PORT without loosing the socket connection, and without over-heating/saturating the "master server", I want it to be clean of all the connections that travel thru it to get to this other server.

What you're making is a TCP proxy. I've written a basic one below. The function getServerBasedOnAddress is where you would pick which server to proxy to. I have just chosen a random one here because I don't know what logic you require.

var net = require('net');

// The servers we will proxy to
var upstreamServerAddresses = [
    {address: '127.0.0.1', port: '3000'},
    {address: '127.0.0.1', port: '3001'},
    {address: '127.0.0.1', port: '3002'},
];

// This is where you pick which server to proxy to
// for examples sake, I choose a random one
function getServerBasedOnAddress(address) {
    return upstreamServerAddresses[Math.floor((Math.random() * 3))]
}

// Create the proxy server
net.createServer(function (socket) {

    socket.on('data', function(data){
        upstream = getServerBasedOnAddress(socket.remoteAddress);
        net.connect(upstream.port, upstream.address, function(connection){
            this.write(data);
        });
    })

}).listen(5000, function(){
    console.log("Ready to proxy data");
});

// Create the upstream servers
for(var i = 0; i < upstreamServerAddresses.length; i++){
    var upstream = upstreamServerAddresses[i];

    net.createServer(function (socket) {
        socket.on('data', function(data){
            console.log("Received some data on " + upstream.address + ":" + upstream.port);
            console.log(data);
        });
    }).listen(upstream.port);
}

As I say, this is a simplistic example. In real life you might want to make some changes, such as not connecting to clients on each packet but rather maintaining a persistent connection. You would probably also want to cover the case where an upstream server was unreachable.

You might also want to use something like the async library to ensure all the clients are up before starting your proxy server so no data is lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM