Nodejs socket client - callback for each request

Asked

Viewed 380 times

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.writeto the server.

I know this whole problem is because Node is asynchronous, how to solve?

1 answer

3

You can use the async.series for that reason:

async.series([function(done){
    client.write('uma mensagem', 'utf8', function(data){
      console.log('primeira mensagem enviada');;
      done();
    });
  },function(done){
    client.write('outra mensagem', 'utf8', function(data){
      console.log('segunda mensagem enviada');
      done();
    });
  },function(done){
    client.write('terceira mensagem', 'utf8', function(data){
      console.log('terceira mensagem enviada');
      done();
    });
  },function(done){
    console.log('todas mensagens enviadas');
    done();
}]);

This code will only send the next message when the previous one receives a reply.

  • 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.

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.