事件:'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'事件。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。