title: Node.js TCP Client command/response
body: <p>I have a simple server, you send it a command, it replies back with an \r\n delimited response.</p>
  
  <p>So I tried to get a command( callback ) method on my client. Check out this simplified code snippet: </p>
  
  <pre><code>var net = require('net');
  
  var Client = function() {
     this.data = "";
     this.stream = net.createConnection(port, host);
  
     this.stream.on('data', function( data ) {
          var self = this;
  
          this.data += data;
          self.process()            
     };
  
     this.process = function() {
         var _terminator = /^([^\r\n]*\r\n)/;
  
         while( results = _terminator.exec(this.data) ) {
              var line = results[1];
              this.data = this.data.slice(line.length);
  
              this.emit('response', data);
         };
     };
  
     this.sendCommand = function( command, callback ) {
         var self = this;
  
         var handler = function( data ) {
              self.removeListener('response', handler);
  
              callback &amp;&amp; callback(data);
         }
  
         this.addListener('response', handler);
  
         this.stream.write(command);
     };
  
     this.command_1 = function( callback ) {
          this.sendCommand( 'test', callback );
     };
  
     this.command_2 = function( callback ) {
          this.sendCommand( 'test2', callback );
     };
  }
  </code></pre>
  
  <p>So I am doing a client.command_1( function() {} ) and then a client.command_2( function() {}) but in the callback of my command_2 I am getting the response from command_1.</p>
  
  <p>Is this the right way to implement such a thing?</p>