事件:'connect'
添加於:v0.7.0
參數
response
<http.IncomingMessage>socket
<stream.Duplex>head
<Buffer>
每次服務器使用 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();
});
});
});
相關用法
- Node.js http.Server 'clientError'事件用法及代碼示例
- Node.js fs.FSWatcher 'change'事件用法及代碼示例
- Node.js MessagePort 'close'事件用法及代碼示例
- Node.js ChildProcess 'close'事件用法及代碼示例
- Node.js tls.Server 'keylog'事件用法及代碼示例
- Node.js cluste 'disconnect'事件用法及代碼示例
- Node.js proces 'exit'事件用法及代碼示例
- Node.js stream.Writable 'pipe'事件用法及代碼示例
- Node.js stream.Readable 'end'事件用法及代碼示例
- Node.js cluste 'fork'事件用法及代碼示例
- Node.js stream.Writable 'unpipe'事件用法及代碼示例
- Node.js Http2Session 'remoteSettings'事件用法及代碼示例
- Node.js Worker 'listening'事件用法及代碼示例
- Node.js tls.Server 'resumeSession'事件用法及代碼示例
- Node.js InterfaceConstructor 'pause'事件用法及代碼示例
- Node.js stream.Readable 'data'事件用法及代碼示例
- Node.js proces 'uncaughtException'事件用法及代碼示例
- Node.js Http2Session 'localSettings'事件用法及代碼示例
- Node.js REPLServer 'exit'事件用法及代碼示例
- Node.js cluste 'online'事件用法及代碼示例
- Node.js tls.TLSSocket 'session'事件用法及代碼示例
- Node.js Worker 'exit'事件用法及代碼示例
- Node.js cluste 'exit'事件用法及代碼示例
- Node.js Http2Stream 'trailers'事件用法及代碼示例
- Node.js http.ClientRequest 'information'事件用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 'connect'事件。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。