Skip to content

Commit e1ddacc

Browse files
authored
[feature] Introduce the WebSocket option (#2007)
Add the ability to use a custom class that extends the `WebSocket` class.
1 parent 8a7016d commit e1ddacc

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

doc/ws.md

+2
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ This class represents a WebSocket server. It extends the `EventEmitter`.
8484
- `verifyClient` {Function} A function which can be used to validate incoming
8585
connections. See description below. (Usage is discouraged: see
8686
[Issue #337](https://github.com/websockets/ws/issues/377#issuecomment-462152231))
87+
- `WebSocket` {Function} Specifies the `WebSocket` class to be used. It must
88+
be extended from the original `WebSocket`. Defaults to `WebSocket`.
8789
- `callback` {Function}
8890

8991
Create a new server instance. One and only one of `port`, `server` or `noServer`

lib/websocket-server.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ class WebSocketServer extends EventEmitter {
4949
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
5050
* not to skip UTF-8 validation for text and close messages
5151
* @param {Function} [options.verifyClient] A hook to reject connections
52+
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
53+
* class to use. It must be the `WebSocket` class or class that extends it
5254
* @param {Function} [callback] A listener for the `listening` event
5355
*/
5456
constructor(options, callback) {
@@ -67,6 +69,7 @@ class WebSocketServer extends EventEmitter {
6769
host: null,
6870
path: null,
6971
port: null,
72+
WebSocket,
7073
...options
7174
};
7275

@@ -356,7 +359,7 @@ class WebSocketServer extends EventEmitter {
356359
`Sec-WebSocket-Accept: ${digest}`
357360
];
358361

359-
const ws = new WebSocket(null);
362+
const ws = new this.options.WebSocket(null);
360363

361364
if (protocols.size) {
362365
//

test/websocket-server.test.js

+26
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,32 @@ describe('WebSocketServer', () => {
8989
wss.close(done);
9090
});
9191
});
92+
93+
it('honors the `WebSocket` option', (done) => {
94+
class CustomWebSocket extends WebSocket.WebSocket {
95+
get foo() {
96+
return 'foo';
97+
}
98+
}
99+
100+
const wss = new WebSocket.Server(
101+
{
102+
port: 0,
103+
WebSocket: CustomWebSocket
104+
},
105+
() => {
106+
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
107+
108+
ws.on('open', ws.close);
109+
}
110+
);
111+
112+
wss.on('connection', (ws) => {
113+
assert.ok(ws instanceof CustomWebSocket);
114+
assert.strictEqual(ws.foo, 'foo');
115+
wss.close(done);
116+
});
117+
});
92118
});
93119

94120
it('emits an error if http server bind fails', (done) => {

0 commit comments

Comments
 (0)