简体   繁体   中英

Manage multiple TCP socket nodejs

I have an array like this:

var exports = module.exports = {};
var net = require('net');

exports.config = [
    {
        ip: "127.0.0.1", 
        id: 1,
        socket:  new net.Socket(),
        data: "",

    },
    {
        ip: "192.168.5.242",    
        id: 2,
        socket:  new net.Socket(),
        data: "",

    }
];

I'm trying to connect each of this items with a TCP socket with this code:

for(var key in tornelli.config) {
    tornelli.config[key].socket.connect(4000, tornelli.config[key].ip, function() {
        console.log('CONNECTED TO: '+tornelli.config[key].ip);

    });

    tornelli.config[key].socket.on('data', function(data) {

       ...........

    });


    tornelli.config[key].socket.on('error', function(error){
         console.log(error);
    });

}

But somethings get wrong because in the console output I get

CONNECTED TO: 192.168.5.242

But actually I'm connected with '127.0.0.1'. It seems that I don't separate each tcp stream. How can I have two separate tcp stream, one every item in this array?

It's somethings about asynchronous execution?

Thanks

In Javascript, for loops are not "blocks". You can put var in there if you want but it will still be "hoisted" to the top of your function. Everything is fine in your initial function calls - key will be 0, and then 1, and the loop will run twice. But when the CALLBACKS are executed, key will always be 1 - its last value. The callbacks are asynchronous, so they will be fired well after the for loop has done its thing.

Javascript has a forEach operator that makes tasks like this simpler. Try the following (or simply break out your socket-handling code to a function that takes the config block as a parameter):

tornelli.config.forEach(function(config) {
    config.socket.connect(4000, config.ip, function() {
        console.log('CONNECTED TO: '+config.ip);
    });

    config.socket.on('data', function(data) {
       ...........
    });

    config.socket.on('error', function(error){
         console.log(error);
    });
}

For what it's worth, it's also really unusual to pre-create things like sockets inside config files. A more standard pattern would be to do the new net.Socket() call inside the above code, not in the config file.

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