http.Agent({ keepAlive: true }) 为什么没有复用客户端连接
发布于 3 天前 作者 yakczh 822 次浏览 最后一次编辑是 2 天前 来自 问答

server.js

const net = require('net');
const server = net.createServer( (client) => {
   console.log(' \t\t\t\t ----> client connected');
   client.on('data', (bytes)=>{
     var seq=bytes.toString('utf-8',6,6+6);
     console.log(seq);
     client.write('HTTP/1.1 200 OK\r\nContent-Length: '+seq.length+'\r\n\r\n'+seq);
  });
 });
server.on('error', (err) => {
 console.log( err);
});
server.listen(8080, () => {
 console.log('server bind 8080');
});

client.js

const http = require('http');
const async = require('async');
const keepAliveAgent = new http.Agent({ keepAlive: true });
var   options={
  hostname: '127.0.0.1',
  host:'127.0.0.1:8080',
  port: 8080,
  path: '/',
  method: 'GET',
  agent: keepAliveAgent,
  headers: {
      'Connection': 'keep-alive'
  }
}
 
var $seq=0; 
function req_seq(next){
	options.path='/?seq='+$seq++
	http.get(options,(resp)=>{
	  resp.on('data', (chunk)=> {
	    console.log('BODY: ' + chunk);
	  });
	});
	 idx=options.path
	 next(null,idx);
}

 
var tasks=[];
for(var i=0;i<10;i++){
  tasks.push(req_seq);
}

async.series(tasks, function(err, result) {
        console.log(result);
});

setTimeout(function(){
  console.log('END');
},9000);

如果http客户端设置 请求头 ‘Connection’: 'keep-alive’
服务端不关闭连接 应该下一次请求应该复用上次的连接 但是运行代码,每次请求还是要重新连接

回到顶部