【问题标题】:Node http request using existing socket使用现有套接字的节点 http 请求
【发布时间】:2016-01-11 17:27:22
【问题描述】:

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

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

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

是否有任何库支持将现有套接字/流用于 HTTP 请求?

【问题讨论】:

    标签: node.js express http-proxy


    【解决方案1】:

    我也遇到过类似的情况。我通过在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;
    }
    

    注意:我没有对示例进行全面测试,因此使用风险自负。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2013-05-14
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多