NodeJS TCP Server, onData small chunks

I made a simple NodeJS TCP server that the Java client sent:

encodedImage = <a base64 encoded image>
out.write("IMG;" + encodedImage);
out.flush();

My NodeJS server is as follows:

net.createServer(function(TCPSocket){
        TCPSocket.on("data", function(data){
            console.log("TCP Recieved: " + data.length);    
        });
}).listen(5000);

However, even if I send all the data and upload it immediately, the output is as follows:

TCP Recieved: 13
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1472
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344

I want it to get it in the simple part, but I assume that this is due to the NodeJS event handling mechanism. What is the best way to get a single piece of data for data sent as one piece? As far as I know, a TCP window can be much larger than 1344 bytes of data. I was thinking of using the header values ​​as HTTP, so I know that declaring the length will create the object I want.

+3
source share
1 answer

, Node . , , , , , . , :

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

net.createServer(function(socket){
  var buffer = new Buffer(0, 'binary');

  socket.on("data", function(data){
    buffer = Buffer.concat([buffer, new Buffer(data,'binary')]);
  });

  socket.on("end", function(data) {
    fs.writeFile("image.jpg", buffer, function(err) {
      if(err) {
        console.log(err);
      } else {
        console.log("Socket[" + socket.name + "] closed, wrote data out to sinfo.data");
      }
    }); 

  });

}).listen(5000);

console.log('ready');

, netcat:

$ netcat localhost 5000 < input.jpg
+7

Source: https://habr.com/ru/post/1692808/


All Articles