从Node.js中的活动套接字重新创建http请求和响应

Recreate http request and response from active Socket in Node js

本文关键字:创建 http 请求 响应 求和 新创建 js Node 活动 套接字      更新时间:2023-09-26

我正在创建一个系统,该系统将http请求传递给Node.js中的子进程。我无法使用child.send('Socket',req.Socket)将活动套接字传递给子进程,但在子进程中,我想重新创建http请求和响应对象,以便它们具有标头、参数、cookie等。

我使用的是Express,所以如果我能重新创建Express req和res对象,那就更好了。

我一直在努力,但没有成功。如果我执行以下操作,它将创建IncomingMessage对象,但标头等为空。

var http = require('http');
/* Child Process recieves the Socket  */
var incomingMessage = new http.IncomingMessage( socket );

如果有什么方法可以实现我想要的,有什么想法吗?

您还可以使用以下隧道技巧:

let agent;
if (protocol == 'https:')
    agent = new https.Agent();
else
    agent = new http.Agent();
agent.createConnection = (opts, callback) => callback(false, socket);
const req = http.request({
    method: method,
    host: host,
    port: port,
    protocol: protocol,
    path: path,
    headers: headers,
    agent: agent
}, function (res)
{
    console.log(res.headers);
    console.log(res.socket.remoteAddress);
    console.log(res.socket == socket); // true
});
req.end();