使用现有套接字来请求http请求

我试图写一个express应用程序,通过SSH隧道代理HTTP请求。 软件包ssh2可以使用forwardOut()创build隧道。 它会创build一个连接到远程机器端口的stream。 我正在尝试通过此连接转发传入的HTTP请求。

我面临的问题是,每个代理库,甚至HTTP库发现创build一个新的套接字到主机,但我想使用来自forwardOut()而不是一个新的套接字的stream。

我可以尝试创build一个额外的服务器,通过隧道转发所有内容,但为每个请求创build额外的套接字听起来很hacky。 我希望有更好的办法。

有什么库支持使用HTTP请求现有的套接字/stream?

我也遇到过类似的情况。 我使用现有的套接字,通过在http.request() (Node.js HTTP客户端)的选项参数中返回由ssh2创build的stream 。 一些示例代码:

 var http = require('http'); var Client = require('ssh2').Client; var conn = new Client(); conn.on('ready', function () { // The connection is forwarded to '0.0.0.0' locally. // Port '0' allows the OS to choose a free TCP port (avoids race conditions) conn.forwardOut('0.0.0.0', 0, '127.0.0.1', 80, function (err, stream) { if (err) throw err; // End connection on stream close stream.on('close', function() { conn.end(); }).end(); // Setup HTTP request parameters requestParams = { host: '127.0.0.1', method: 'GET', path: '/', createConnecion: function() { return stream; // This is where the stream from ssh2 is passed to http.request() } }; var request = http.request(requestParams, function(response) { response.on('data', function (chunk) { // Do whatever you need to do with 'chunk' (the response body) // Note, this may be called more than once if the response data is long }) }); // Send request request.end(); }); }).connect({ host: '127.0.0.1', username: 'user', password: 'password' }); 

我有一个问题,没有定义socket.destroySoon() ,因为它可以在stream返回之前定义的解决方法。 它只是简单地调用socket.destroy() 。 例:

 createConnection: function () { stream.destroySoon = function () { return stream.destroy(); } return stream; } 

注意:我没有完全testing这些例子,所以请自担风险。