3
I have the following code
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
I need to send several messages at once to the server and I need to process each of the answers, it turns out that Node is asynchronous, I mean, I don’t have a response order. the commands below trigger the event client.on('data'function(data) {...
however I can not know exactly the response of each request, the ideal would be to execute synchronously but not to be able.
client.write('Algumacoisa1');
client.write('Algumacoisa2');
client.write('Algumacoisa3');
By the manual net socket socket.write(data[, encoding][, callback])
I saw that I can use it like this :
client.write('algumacoisa', 'utf8', function(data){
console.log(data); //data sempre é undefined
})
summing up, I want for each client.write
I get your reply and only then I send more client.write
to the server.
I know this whole problem is because Node is asynchronous, how to solve?
From what I understand, I send an array of functions to be executed, blz, but the problem is that these functions will execute the measures that are sent requests, so this array is dynamic. If the guy sends a request, then I run it with the async, blz, but then another request is sent, will I run the async again? I’m thinking the solution will be to use a stack of requests.
– Rodrigo Rodrigues
I updated the response with the link to the async.series. Each array item is a function, which is executed in sequence, one after the other. Running the above code you will have the output messages always in the same sequence as you had asked.
– Vitor George