当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js http.ClientRequest 'connect'事件用法及代码示例


事件:'connect'

添加于:v0.7.0

参数

每次服务器使用 CONNECT 方法响应请求时发出。如果未侦听此事件,则接收 CONNECT 方法的客户端将关闭其连接。

除非用户指定 <net.Socket> 以外的套接字类型,否则此事件保证会传递 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类。

演示如何侦听 'connect' 事件的客户端和服务器对:

const http = require('node:http');
const net = require('node:net');
const { URL } = require('node:url');

// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
proxy.on('connect', (req, clientSocket, head) => {
  // Connect to an origin server
  const { port, hostname } = new URL(`http://${req.url}`);
  const serverSocket = net.connect(port || 80, hostname, () => {
    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                    'Proxy-agent: Node.js-Proxy\r\n' +
                    '\r\n');
    serverSocket.write(head);
    serverSocket.pipe(clientSocket);
    clientSocket.pipe(serverSocket);
  });
});

// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {

  // Make a request to a tunneling proxy
  const options = {
    port: 1337,
    host: '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('got connected!');

    // Make a request over an HTTP tunnel
    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();
    });
  });
});

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品  'connect'事件。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。