这段代码发出两个请求。但是,它们使用不同的套接字。如何配置Server
或请求Agent
,以便两个请求使用同一个套接字?
import { Server, IncomingMessage, ServerResponse, Agent, request } from 'node:http';
import { Socket } from 'node:net';
console.log('\n\n');
let server = new Server({ keepAlive: true});
server.addListener('request', (req: IncomingMessage, res: ServerResponse) => {
console.log('Server_request');
console.log(req.headers);
console.log('IncomingMessage.socket.remotePort', req.socket.remotePort);
let data = '';
req.addListener('data', (chunk: string) => {
console.log('IncomingMessage_data');
data = data + chunk;
})
req.addListener('close', () => {
console.log('IncomingMessage_close');
});
req.addListener('end', () => {
console.log('IncomingMessage_end');
res.end('');
});
})
server.listen(3000, "127.0.0.1");
server.addListener('close', () => console.log('sever_close'));
server.addListener('connection', (socket: Socket) => {
// "This event is emitted when a new TCP stream is established (https://nodejs.org/api/http.html#event-connection)."
socket.addListener('close', () => console.log('Socket_close'));
console.log("Socket.localPort", socket.localPort);
console.log("Socket.remotePort", socket.remotePort);
})
let agent = new Agent({ keepAlive: true, maxSockets: 1});
let req0 = request(
{
agent: agent,
hostname: '127.0.0.1',
port: 3000,
path: '/',
method: 'POST'
}, (res:IncomingMessage)=>{
console.log(res.headers);
});
req0.end("0");
let req1 = request(
{
agent: agent,
hostname: '127.0.0.1',
port: 3000,
path: '/',
method: 'POST'
}, (res:IncomingMessage)=>{
console.log(res.headers);
});
req1.end("1");
这是一个可能的结果:
Socket.localPort 3000
Socket.remotePort 38880
Server_request
{
host: '127.0.0.1:3000',
connection: 'keep-alive',
'content-length': '1'
}
IncomingMessage.socket.remotePort 38880
IncomingMessage_data
IncomingMessage_end
IncomingMessage_close
{
date: 'Sun, 21 May 2023 18:53:56 GMT',
connection: 'keep-alive',
'keep-alive': 'timeout=5',
'content-length': '0'
}
Socket_close
Socket.localPort 3000
Socket.remotePort 34564
Server_request
{
host: '127.0.0.1:3000',
connection: 'keep-alive',
'content-length': '1'
}
IncomingMessage.socket.remotePort 34564
IncomingMessage_data
IncomingMessage_end
IncomingMessage_close
{
date: 'Sun, 21 May 2023 18:54:01 GMT',
connection: 'keep-alive',
'keep-alive': 'timeout=5',
'content-length': '0'
}
Socket_close
1条答案
按热度按时间xam8gpfp1#
这里的“诀窍”是引流响应;这允许随后的请求在其关闭之前使用相同的套接字(即,res.resume();):