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

    每次服务器响应升级请求时发出。 如果未监听此事件且响应状态码为 101 Switching Protocols,则接收升级响应头的客户端将关闭其连接。

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

    客户端服务器对,演示如何监听 'upgrade' 事件。

    1. const http = require('http');
    2. // 创建 HTTP 服务器。
    3. const server = http.createServer((req, res) => {
    4. res.writeHead(200, { 'Content-Type': 'text/plain' });
    5. res.end('响应内容');
    6. });
    7. server.on('upgrade', (req, socket, head) => {
    8. socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
    9. 'Upgrade: WebSocket\r\n' +
    10. 'Connection: Upgrade\r\n' +
    11. '\r\n');
    12. socket.pipe(socket); // 响应回去。
    13. });
    14. // 服务器正在运行。
    15. server.listen(1337, '127.0.0.1', () => {
    16. // 发送请求。
    17. const options = {
    18. port: 1337,
    19. host: '127.0.0.1',
    20. headers: {
    21. 'Connection': 'Upgrade',
    22. 'Upgrade': 'websocket'
    23. }
    24. };
    25. const req = http.request(options);
    26. req.end();
    27. req.on('upgrade', (res, socket, upgradeHead) => {
    28. console.log('接收到响应');
    29. socket.end();
    30. process.exit(0);
    31. });
    32. });