| 314 | } |
| 315 | |
| 316 | _connectWebsocket(urlPath) { |
| 317 | this.reset(); |
| 318 | |
| 319 | const requestKey = crypto.randomBytes(16).toString('base64'); |
| 320 | debuglog('request WebSocket', requestKey); |
| 321 | |
| 322 | const httpReq = this._http = http.request({ |
| 323 | host: this._host, |
| 324 | port: this._port, |
| 325 | path: urlPath, |
| 326 | headers: { |
| 327 | 'Connection': 'Upgrade', |
| 328 | 'Upgrade': 'websocket', |
| 329 | 'Sec-WebSocket-Key': requestKey, |
| 330 | 'Sec-WebSocket-Version': '13', |
| 331 | }, |
| 332 | }); |
| 333 | httpReq.on('error', (e) => { |
| 334 | this.emit('error', e); |
| 335 | }); |
| 336 | httpReq.on('response', (httpRes) => { |
| 337 | if (httpRes.statusCode >= 400) { |
| 338 | process.stderr.write(`Unexpected HTTP code: ${httpRes.statusCode}\n`); |
| 339 | httpRes.pipe(process.stderr); |
| 340 | } else { |
| 341 | httpRes.pipe(process.stderr); |
| 342 | } |
| 343 | }); |
| 344 | |
| 345 | const handshakeListener = (res, socket) => { |
| 346 | validateHandshake(requestKey, res.headers['sec-websocket-accept']); |
| 347 | debuglog('websocket upgrade'); |
| 348 | |
| 349 | this._socket = socket; |
| 350 | socket.on('data', this.handleChunk); |
| 351 | socket.on('close', () => { |
| 352 | this.emit('close'); |
| 353 | }); |
| 354 | |
| 355 | this.emit('ready'); |
| 356 | }; |
| 357 | |
| 358 | const onReady = once(this, 'ready'); |
| 359 | httpReq.on('upgrade', handshakeListener); |
| 360 | httpReq.end(); |
| 361 | return onReady; |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | module.exports = Client; |