Node.js http模块不接收WS请求(使用https-proxy-agent)

时间:2018-04-15 14:24:26

标签: node.js websocket https-proxy-agent

概念很简单,创建一个将websocket请求转发到另一个端口的http服务器。

以下是我服务器端的代码:

  http.createServer(onRequest).listen(9999);
  function onRequest(request, response) {
    console.log(request);
    ...
  }

因此,如果http服务器完全收到任何请求,它应该在控制台中打印出请求。

然后在客户端(也是node.js应用程序),代码是:

    var HttpsProxyAgent = require('https-proxy-agent');
    var WebSocket = require('ws');
    ...
    var proxy = `http://${config.proxy.host}:${config.proxy.port}`;
    var options = url.parse(proxy);
    agent = new HttpsProxyAgent(options);
    ws = new WebSocket(target, {
      protocol: 'binary',
      agent: agent
    });

现在,当我使用Charles拦截请求时,客户端确实发出了请求,这是查尔斯捕获的卷曲形式:

curl -H'Host:target.host.com:8080'-X CONNECT'https://target.host.com:8080'

问题似乎是那个

  function onRequest(request, response) {
    console.log(request);
    ...
  }

实际上没有收到任何-X CONNECT 'https://proxy.host.com:9999'请求,或者至少它没有打印出来(显然它也没有用)。

1 个答案:

答案 0 :(得分:1)

  var server = http.createServer(onRequest).listen(9999);
  server.on('connect', (req, cltSocket, head) => {
    const srvSocket = net.connect('8080', '127.0.0.1', () => {
      cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                      'Proxy-agent: Node.js-Proxy\r\n' +
                      '\r\n');
      srvSocket.write(head);
      srvSocket.pipe(cltSocket);
      cltSocket.pipe(srvSocket);
    });
  });