title: Nodejs as a client to a Request/Response server via socket
body: <p>I am trying to build a webserver with sailsjs.</p>
  
  <p>In order to perform its request, my server needs to connect to a socket to pass commands and wait for reponses.</p>
  
  <p>For each command, I wait for a specific response and have to call a specific callback. Currently I only open one socket and change the "onData" socket at each request. It looks like it does not work well and is ugly. </p>
  
  <p>Another option could be to open and close a socket for each command or request : I find it even worst.</p>
  
  <p>Is there a clever way to do what I need ?</p>
  
  <p><strong>Edited:</strong></p>
  
  <p>Here is the socket (DriverConnection.js):</p>
  
  <pre><code>module.exports = {
  
      connect: function(callback){
          var net = require('net');
          client = net.connect({port: 13}, function() { //'connect' listener
              console.log('client connected');
              callback();
          });
      },
  
    command: function(command, callback){
      client.write(command);
      client.on('data', function(data) {
        console.log("parsing data " + data.toString());
        callback(JSON.parse(data.toString()));
      });
    }
  
  };
  </code></pre>
  
  <p>Here is a example of its request usage :</p>
  
  <pre><code>module.exports = {
  
      list: function(req,res) {
        DriverConnection.command('{}',function(data){
          for(key in data) {
            var mac = data[key];
            Autoreez.findOne({name : mac},function (err,auto){
              if(!auto) {
                User.create({name : mac}, function(err,user){
                  res.send(user);
                });
              } else {
                res.send(auto);
              }
            });
          }
        });
      },
  }
  </code></pre>