* Upgrade the connection to WebSocket. * * @param {Object} extensions The accepted extensions * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Set} protocols The subprotocols * @param {http.IncomingMessage} req The request object * @param {Duplex} socket
(extensions, key, protocols, req, socket, head, cb)
| 370 | * @private |
| 371 | */ |
| 372 | completeUpgrade(extensions, key, protocols, req, socket, head, cb) { |
| 373 | // |
| 374 | // Destroy the socket if the client has already sent a FIN packet. |
| 375 | // |
| 376 | if (!socket.readable || !socket.writable) return socket.destroy(); |
| 377 | |
| 378 | if (socket[kWebSocket]) { |
| 379 | throw new Error( |
| 380 | 'server.handleUpgrade() was called more than once with the same ' + |
| 381 | 'socket, possibly due to a misconfiguration' |
| 382 | ); |
| 383 | } |
| 384 | |
| 385 | if (this._state > RUNNING) return abortHandshake(socket, 503); |
| 386 | |
| 387 | const digest = createHash('sha1') |
| 388 | .update(key + GUID) |
| 389 | .digest('base64'); |
| 390 | |
| 391 | const headers = [ |
| 392 | 'HTTP/1.1 101 Switching Protocols', |
| 393 | 'Upgrade: websocket', |
| 394 | 'Connection: Upgrade', |
| 395 | `Sec-WebSocket-Accept: ${digest}` |
| 396 | ]; |
| 397 | |
| 398 | const ws = new this.options.WebSocket(null, undefined, this.options); |
| 399 | |
| 400 | if (protocols.size) { |
| 401 | // |
| 402 | // Optionally call external protocol selection handler. |
| 403 | // |
| 404 | const protocol = this.options.handleProtocols |
| 405 | ? this.options.handleProtocols(protocols, req) |
| 406 | : protocols.values().next().value; |
| 407 | |
| 408 | if (protocol) { |
| 409 | headers.push(`Sec-WebSocket-Protocol: ${protocol}`); |
| 410 | ws._protocol = protocol; |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | if (extensions[PerMessageDeflate.extensionName]) { |
| 415 | const params = extensions[PerMessageDeflate.extensionName].params; |
| 416 | const value = extension.format({ |
| 417 | [PerMessageDeflate.extensionName]: [params] |
| 418 | }); |
| 419 | headers.push(`Sec-WebSocket-Extensions: ${value}`); |
| 420 | ws._extensions = extensions; |
| 421 | } |
| 422 | |
| 423 | // |
| 424 | // Allow external modification/inspection of handshake headers. |
| 425 | // |
| 426 | this.emit('headers', headers, req); |
| 427 | |
| 428 | socket.write(headers.concat('\r\n').join('\r\n')); |
| 429 | socket.removeListener('error', socketOnError); |
no test coverage detected