當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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'事件。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。