Node.js how to handle packet fragmentation with ne

2019-05-25 01:01发布

问题:

When a net.Server receives data that exceeds 1500 bytes (default mtu), the 'on data' event is executed with each fragment of the packet. Is there a way to receive the whole packet in a single 'on data' call?

Thanks.

回答1:

Try this

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

var socktimeout = 600000;
var svrport = your_port;

var svr = net.createServer(function(sock) {
  var mdata = new Buffer(0);
    //sys.puts('Connected: ' + sock.remoteAddress + ':' + sock.remotePort); 
     sock.setTimeout(socktimeout,function(){
            sock.end("timeout");
            sock.destroy();
        });

    sock.on('data', function(data) {  


        if(mdata.length != 0)
        {
          var tempBuf = Buffer.concat([mdata, data]);
          mdata = tempBuf;
        }
        else
        {
          mdata = data;
        }

        var len=got_your_Packget_length(mdata);
         
      if(mdata.length == len)
      {
        do_your_job(mdata)
        mdata = new Buffer(0);
      }


    });
 


    sock.on('error', function(err) { // Handle the connection error.
        sys.puts('error: ' + err +'\n');
    });
});
 
svr.listen(svrport);