事件:'upgrade'
添加于:v0.1.94
参数
response<http.IncomingMessage>socket<stream.Duplex>head<Buffer>
每次服务器响应升级请求时发出。如果未侦听此事件且响应状态代码为 101 Switching Protocols,则接收到升级标头的客户端将关闭其连接。
除非用户指定 <net.Socket> 以外的套接字类型,否则此事件保证会传递 <net.Socket> 类的实例,该类是 <stream.Duplex> 的子类。
演示如何侦听 'upgrade' 事件的客户端服务器对。
const http = require('node:http');
// Create an HTTP server
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
server.on('upgrade', (req, socket, head) => {
  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
               'Upgrade: WebSocket\r\n' +
               'Connection: Upgrade\r\n' +
               '\r\n');
  socket.pipe(socket); // echo back
});
// Now that server is running
server.listen(1337, '127.0.0.1', () => {
  // make a request
  const options = {
    port: 1337,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };
  const req = http.request(options);
  req.end();
  req.on('upgrade', (res, socket, upgradeHead) => {
    console.log('got upgraded!');
    socket.end();
    process.exit(0);
  });
});
相关用法
- Node.js stream.Writable 'unpipe'事件用法及代码示例
 - Node.js proces 'uncaughtException'事件用法及代码示例
 - Node.js proces 'uncaughtExceptionMonitor'事件用法及代码示例
 - Node.js proces 'unhandledRejection'事件用法及代码示例
 - Node.js tls.Server 'keylog'事件用法及代码示例
 - Node.js http.Server 'clientError'事件用法及代码示例
 - Node.js cluste 'disconnect'事件用法及代码示例
 - Node.js proces 'exit'事件用法及代码示例
 - Node.js stream.Writable 'pipe'事件用法及代码示例
 - Node.js stream.Readable 'end'事件用法及代码示例
 - Node.js cluste 'fork'事件用法及代码示例
 - Node.js Http2Session 'remoteSettings'事件用法及代码示例
 - Node.js Worker 'listening'事件用法及代码示例
 - Node.js tls.Server 'resumeSession'事件用法及代码示例
 - Node.js InterfaceConstructor 'pause'事件用法及代码示例
 - Node.js fs.FSWatcher 'change'事件用法及代码示例
 - Node.js stream.Readable 'data'事件用法及代码示例
 - Node.js http.ClientRequest 'connect'事件用法及代码示例
 - 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'事件用法及代码示例
 
注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 'upgrade'事件。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
