0

Hi i've been asked to make an array of servers listening to some ports, the problem here is that when I use:

"serviceSocket.connect(parseInt(80),"elpais.es",

what I really need is to use the adress and remotePorts arrays. Like this:

"serviceSocket.connect(remotePort[i],adress[i])

but I'm not able to pass that information to serviceSocket. Besides, when I try to get the port that has been trigered with server.address() (for example, I connect through 8002), all the time what I'm getting in return is 8008.

How can I get the right port, or pass the information?

var ports = [8001,8002,8003,8004,8005,8006,8007,8008];
var adress = ["www.cnc.uji.es","en.wikipedia.org","random.random2.es","ftp.rediris.es", "elpais.es" ,"","",""]
var remotePort = [80,80,443,21,80,"","",""]

for (i=0 ;i<ports.length; i++){

  var server = net.createServer(function(socket){

        socket.on('data', function(data){
console.log(server.address());
            var serviceSocket = new net.Socket();
    serviceSocket.connect(parseInt(80),"elpais.es", function(){
serviceSocket.write(data);});
    serviceSocket.on('data',function(data){console.log(server.address());
socket.write(data);});
        });
        }).listen(ports[i]);
}
console.log('TCP server accepting connection on port ' + ports)
pablo
  • 29
  • 5
  • possible duplicate of [JavaScript closures vs. anonymous functions](http://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions) – Louis Jan 13 '14 at 16:30

1 Answers1

0

your code is running asynchronously and when the callback function calls i,the for loop's already finished so that's why you always get the last element of the array.

try something like this

var net = require('http');
var ports = [8001,8002,8003,8004,8005,8006,8007,8008];
var adress = ["www.cnc.uji.es","en.wikipedia.org","random.random2.es","ftp.rediris.es",     "elpais.es" ,"","",""];
var remotePort = [80,80,443,21,80,"","",""];

for (i=0 ;i<ports.length; i++){
makeServer(i);
}
console.log('TCP server accepting connection on port ' + ports);

function makeServer(i){
    var server = net.createServer(function(socket){
        socket.on('data', function(data){
console.log(server.address());
        var serviceSocket = new net.Socket();
serviceSocket.connect(parseInt(80),"elpais.es", function(){
serviceSocket.write(data);});
    serviceSocket.on('data',function(data){console.log(server.address());
socket.write(data);});
        });
        }).listen(ports[i]);

};

code isn't tested.

suish
  • 3,253
  • 1
  • 15
  • 34