NodeJS socket client - callback for each request

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 responses, it happens that the node is asynchronous, that is, I do not have a response order. the commands below triggers the client.on('data'function(data) {... event but I can not know exactly the response of each request, ideally it should be run synchronously but can not.

   client.write('Algumacoisa1');
   client.write('Algumacoisa2');
   client.write('Algumacoisa3');

By the net socket manual I can use as follows:

  client.write('algumacoisa', 'utf8', function(data){
     console.log(data); //data sempre é undefined

   })

In short, I want for every socket.write(data[, encoding][, callback]) I receive your response and only then send client.write to the server.

I know that this whole problem is because the node is asynchronous, how to solve it?

    
asked by anonymous 11.07.2015 / 05:29

1 answer

3

You can use async.series for this:

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.

    
13.07.2015 / 21:40