Tuesday, 2 May 2017

Node using net module as a tcp client

I need to create a tcp client to send data to the server five times with different contents. And the last two contents are based on the previous one.

Basically I want to send data to tcp server five times synchronously.

I did it like this, but it's looking silly. Anyone can tell me the correct way to do it. My codes:

var str = ["one","two","three","four","five"];
client.connect(port, ip, function() {
client.on('data', function(data) {
    temp = data.toString();
    console.log(temp);
    });
    client.write(str[0]);
    setTimeout(function() {
        client.write(str[1]);
        client.on('data', function(data) {
        temp = data.toString();
        console.log(temp);
        });
    }, 2000);
    setTimeout(function() {
        client.write(str[2]);
    }, 4000);
    setTimeout(function() {    
        sess = temp.split("Session:")[1].split(";")[0];
        var str2 = str[3] + sess + "\r\n";
        client.write(str2);
        }
    }, 6000);
    setTimeout(function() {
        var sess = temp.split("Session:")[1].split(";")[0];
        var str3 = str[4] + sess + "Range: npt=0.000-\r\n";
        console.log(str3);
        client.write(str3);
        }
    }, 8000);
});



via Huyin Dong

No comments:

Post a Comment