title: Send file over tcp socket via proxy with streams
body: <p>What i tried to achieve with node.js/io.js, is to send a file from one server to another one via a proxy. To avoid memory buffering i want to use streams.</p>
  
  <p>The proxy should be able to connect to multiple targets dynamically. The target connection information for the proxy should be send prior to the filedata. </p>
  
  <p>With normal socket communication and buffering it is not a problem. But how or in general can this be done with streams??</p>
  
  <pre><code>var net = require('net');
  var fs = require('fs');
  
  //create readstream from file
  var myFile = fs.createReadStream('E:/sample.tar.gz');
  
  // Proxy server
  //####################################################################################################
  
  var proxy = net.createServer(function (socket) {
  
      // Create a new connection to the TCP server
     var client = net.connect('9010'); 
     // 2-way pipe between client and TCP server
     socket.pipe(client).pipe(socket);
  
  }).listen(9000);
  
  
  // Targetserver
  //####################################################################################################
  
  var server = net.createServer(function (socket) {
  
      // create filestream to write data into file
      var destfile = fs.createWriteStream('E:/sample_copy.tar.gz')
  
      socket.on('data', function (buffer) {
  
          console.log('Get data on targetserver...');
          // write buffer to file    
          destfile.write(buffer);
  
      });
  
      socket.on('end', function () {
          // release file from writestream
          destfile.end();
       });
  
  }).listen(9010);
  
  
  // Client
  //####################################################################################################
  
  // Send file to proxy
  var client = new net.Socket();
  
  // connect to proxy
  client.connect('9000', '127.0.0.1', function () {
  
      console.log('Connection to proxy opened');
  
  });
  
  // send data to proxy
  myFile.pipe(client);
  
  // read response from taget
  client.on('data', function(data) {
  
      console.log('Response: ' + data);
      // close the client socket completely
      client.destroy();
  
  });
  
  // Add a 'close' event handler for the client socket
  client.on('close', function() {
      console.log('Connection to proxy closed');
  });
  </code></pre>
  
  <p>Any hint to a good tutorial is also welcome.</p>
  
  <p>TMOE</p>