节点js,模块网,服务器阵列

时间:2014-01-13 16:14:38

标签: node.js

您好我被要求制作一组服务器来监听某些端口,这里的问题是当我使用时:

“serviceSocket.connect(parseInt函数(80),” elpais.es”,

我真正需要的是使用地址和remotePorts数组。 像这样:

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

但我无法将该信息传递给serviceSocket。 此外,当我尝试使用server.address()获取已经被触发的端口时(例如,我通过8002连接),我得到的回报总是8008.

如何获得正确的端口或传递信息?

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)

1 个答案:

答案 0 :(得分:0)

你的代码是异步运行的,当回调函数调用i时,for循环已经完成,这就是为什么你总是得到数组的最后一个元素。

尝试这样的事情

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]);

};

代码未经过测试。