node.js - 使用现有套接字的 Node http请求

标签 node.js express http-proxy

我正在尝试编写一个 express 应用程序,它通过 ssh 隧道代理 HTTP 请求。包 ssh2 可以使用 forwardOut() 创建隧道。它创建一个连接到远程计算机上的端口的流。我现在尝试通过此连接转发传入的 HTTP 请求。

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

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

是否有任何库支持使用现有套接字/流进行 HTTP 请求?

最佳答案

我也遇到过类似的情况。我通过在 http.request() (Node.js HTTP 客户端)的选项参数中返回由 ssh2 创建的 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;
}

注意:我尚未完全测试这些示例,因此使用时需要您自担风险。

关于node.js - 使用现有套接字的 Node http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34727556/

相关文章:

javascript - Node.js 模块加载

python - requests.exceptions.SSLError : [Errno 8] _ssl. c:504: EOF 发生违反协议(protocol)

javascript - Express 服务器 404ing 所有来自索引的请求

node.js - 新鲜 meteor 1.3 在 win 7 上无法运行

ReST 低延迟 - 我应该如何在上传挂起时回复 GET?

node.js - NPM 锁定文件无法正确处理传递依赖项

node.js - 类型错误 : 'connect' only accepts a callback

node.js - Electron-Builder:在MacOS上使用松鼠构建Windows安装程序失败

javascript - 如何使用 MERN 堆栈构建动态单页 Web 应用程序?

javascript - Express + socket.io + mongoDB 有哪些架构选择