• response {http.IncomingMessage}
    • socket {stream.Duplex}
    • head {Buffer}

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

    此事件保证传入 {net.Socket} 类({stream.Duplex} 的子类)的实例,除非用户指定了 {net.Socket} 以外的套接字类型。

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

    1. const http = require('http');
    2. const net = require('net');
    3. const { URL } = require('url');
    4. // 创建 HTTP 隧道代理。
    5. const proxy = http.createServer((req, res) => {
    6. res.writeHead(200, { 'Content-Type': 'text/plain' });
    7. res.end('响应内容');
    8. });
    9. proxy.on('connect', (req, clientSocket, head) => {
    10. // 连接到原始服务器。
    11. const { port, hostname } = new URL(`http://${req.url}`);
    12. const serverSocket = net.connect(port || 80, hostname, () => {
    13. clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
    14. 'Proxy-agent: Node.js-Proxy\r\n' +
    15. '\r\n');
    16. serverSocket.write(head);
    17. serverSocket.pipe(clientSocket);
    18. clientSocket.pipe(serverSocket);
    19. });
    20. });
    21. // 代理正在运行。
    22. proxy.listen(1337, '127.0.0.1', () => {
    23. // 向隧道代理发出请求。
    24. const options = {
    25. port: 1337,
    26. host: '127.0.0.1',
    27. method: 'CONNECT',
    28. path: 'nodejs.cn:80'
    29. };
    30. const req = http.request(options);
    31. req.end();
    32. req.on('connect', (res, socket, head) => {
    33. console.log('已连接');
    34. // 通过 HTTP 隧道发出请求。
    35. socket.write('GET / HTTP/1.1\r\n' +
    36. 'Host: nodejs.cn:80\r\n' +
    37. 'Connection: close\r\n' +
    38. '\r\n');
    39. socket.on('data', (chunk) => {
    40. console.log(chunk.toString());
    41. });
    42. socket.on('end', () => {
    43. proxy.close();
    44. });
    45. });
    46. });