Creative Choi Creative Choi - 1 month ago 8
Node.js Question

Received data from HTTP client is lost while sending it to a TCP server

I have one http server and one tcp server both by simple node.js code.
But when I pass some data to tcp from http, I cannot get correct file.
Files are always broken.

When I tested pass an image file from local, it works fine for me.
So, the problem I think is upload.js but I cannot fild my fault.

Please help.

[upload.js] - http server

var server = http.createServer(function(request, response){

/* my html form is
<form method="POST" action="/upload" enctype="multipart/form-data">
*/

if(request.url == '/upload') {

request.on('data', function(data){
var client = net.createConnection({ port: 1234 }, function(){
client.write(data);
client.end()
});
})

}
});
server.listen(1000);


[save.js] - tcp server

var net = require('net');
var fs = require('fs');

var server = net.createServer(function(c){
var img = fs.createWriteStream('a.jpg',
{ defaultEncoding: 'binary' }
);
c.on('data', function(data){
img.write(data);
});

c.on('end', function(){
});
});

server.listen(1234);

Answer

This occurs since you are not saving the entire expected file, but only chunks of it. You are actually creating a new connection and recreating the same file on the TCP server's side every time you receive a chunk.

You should create a global img var on the HTTP server side, store the chunks inside it, then initiate the TCP connection only when the transfer ends.

var img = [];
var server = http.createServer(function(request, response){

    /* my html form is 
        <form method="POST" action="/upload" enctype="multipart/form-data">
    */

    if(request.url == '/upload') {

        request.on('data', function(data){
             img.push(data);
        }).on('end', function () {
             var bytes = Buffer.concat(img);
             var client = net.createConnection({ port: 1234 }, function(){
                 client.write(bytes, function () {
                     client.end();
                 });
             });
        });

    }
});
server.listen(1000);

The TCP server should be fine, except that you should close the stream when you don't need it anymore.

c.on('end', function(){
    img.end();
});
Comments