V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
linxiaoziruo
V2EX  ›  问与答

nodejs 官网代码问题

  •  
  •   linxiaoziruo · 2018-08-16 14:43:47 +08:00 · 805 次点击
    这是一个创建于 2073 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面代码不能运行。

    const http = require('http');
    const net = require('net');
    const url = require('url');
    
    // 创建一个 HTTP 代理服务器
    const proxy = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('okay');
    });
    proxy.on('connect', (req, cltSocket, head) => {
      // 连接到一个服务器
      const srvUrl = url.parse(`http://${req.url}`);
      const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
        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);
      });
    });
    
    // 代理服务器正在运行
    proxy.listen(1337, '127.0.0.1', () => {
    
      // 发送一个请求到代理服务器
      const options = {
        port: 1337,
        hostname: '127.0.0.1',
        method: 'CONNECT',
        path: 'www.google.com:80'
      };
    
      const req = http.request(options);
      req.end();
    
      req.on('connect', (res, socket, head) => {
        console.log('已连接!');
    
        // 通过代理服务器发送一个请求
        socket.write('GET / HTTP/1.1\r\n' +
                     'Host: www.google.com:80\r\n' +
                     'Connection: close\r\n' +
                     '\r\n');
        socket.on('data', (chunk) => {
          console.log(chunk.toString());
        });
        socket.on('end', () => {
          proxy.close();
        });
      });
    });
    
    Skin
        1
    Skin  
       2018-08-16 22:55:29 +08:00
    你确定连上谷歌没问题?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   876 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 21:46 · PVG 05:46 · LAX 14:46 · JFK 17:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.