NodeJS 如何使用同一个socket发出两个请求?

5us2dqdw  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(131)

这段代码发出两个请求。但是,它们使用不同的套接字。如何配置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
xam8gpfp

xam8gpfp1#

这里的“诀窍”是引流响应;这允许随后的请求在其关闭之前使用相同的套接字(即,res.resume();):

import { Server, IncomingMessage, ServerResponse, Agent, request } from 'node:http';
import { Socket } from 'node:net';

console.log('\n\n');

let server = new Server({ keepAlive: true, keepAliveTimeout: 4000 });

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('Server_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, timeout: 2000 });

// The agent will keep the socket open for 2 seconds.
let req0 = request(
    {
        agent: agent,
        hostname: '127.0.0.1',
        port: 3000,
        path: '/',
        method: 'POST'
    }, (res: IncomingMessage) => {
        console.log(res.headers);
        res.resume();
    });

req0.end("0");

// The Socket is still open; hence, make another request using the same destination port number (i.e., the same socket).
let req1 = request(
    {
        agent: agent,
        hostname: '127.0.0.1',
        port: 3000,
        path: '/',
        method: 'POST'
    }, (res: IncomingMessage) => {
        console.log(res.headers);
        res.resume();
        // Drain the Readable.
    });

req1.end("1");

setTimeout(() => {
    // Use the same agent to make another request.
    // The Socket has been closed (> 2000ms); hence, this request will likely have a different destination port number (i.e., a new Socket).
    let req2 = request(
        {
            agent: agent,
            hostname: '127.0.0.1',
            port: 3000,
            path: '/',
            method: 'POST'
        }, (res: IncomingMessage) => {
            console.log(res.headers);
            res.resume();
            // Drain the Readable.
        });

    req2.end("2");
}, 5000);

相关问题