diff --git a/doc/ws.md b/doc/ws.md index fc14e7e97..051ac8235 100644 --- a/doc/ws.md +++ b/doc/ws.md @@ -219,7 +219,7 @@ tracking is disabled. In this case the `'close'` event is emitted in the next tick. The optional callback is called when the `'close'` event occurs and receives an `Error` if the server is already closed. -### server.handleUpgrade(request, socket, head, callback) +### server.handleUpgrade(request, socket, head[, callback]) - `request` {http.IncomingMessage} The client HTTP GET request. - `socket` {net.Socket} The network socket between the server and client. @@ -236,6 +236,9 @@ If the upgrade is successful, the `callback` is called with two arguments: - `websocket` {WebSocket} A `WebSocket` object. - `request` {http.IncomingMessage} The client HTTP GET request. +If the `callback` is not provided the [`'connection'`](#event-connection) event +is emitted instead. + ### server.shouldHandle(request) - `request` {http.IncomingMessage} The client HTTP GET request. diff --git a/lib/websocket-server.js b/lib/websocket-server.js index 3c7939f28..f667b9f9e 100644 --- a/lib/websocket-server.js +++ b/lib/websocket-server.js @@ -102,14 +102,10 @@ class WebSocketServer extends EventEmitter { } if (this._server) { - const emitConnection = this.emit.bind(this, 'connection'); - this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } + upgrade: this.handleUpgrade.bind(this) }); } @@ -221,7 +217,7 @@ class WebSocketServer extends EventEmitter { * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback + * @param {Function} [cb] Callback * @public */ handleUpgrade(req, socket, head, cb) { @@ -326,7 +322,7 @@ class WebSocketServer extends EventEmitter { * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback + * @param {Function} [cb] Callback * @throws {Error} If called more than once with the same socket * @private */ @@ -405,7 +401,11 @@ class WebSocketServer extends EventEmitter { }); } - cb(ws, req); + if (typeof cb === 'function') { + cb(ws, req); + } else { + this.emit('connection', ws, req); + } } }