Node.js how to handle packet fragmentation with net.Server

て烟熏妆下的殇ゞ 提交于 2020-01-13 04:31:09

问题


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);


来源:https://stackoverflow.com/questions/24858900/node-js-how-to-handle-packet-fragmentation-with-net-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!