Skip to content

Commit

Permalink
[api] Add WebSocketServer.prototype.address() (#1294)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tossapon Nuanchuay authored and lpinca committed Feb 5, 2018
1 parent 66b0d55 commit 8d61fa0
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
8 changes: 8 additions & 0 deletions doc/ws.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@ Emitted when the underlying server has been bound.
A set that stores all connected clients. Please note that this property is only
added when the `clientTracking` is truthy.

### server.address()

Returns an object with `port`, `family`, and `address` properties specifying
the bound address, the address family name, and port of the server as reported
by the operating system if listening on an IP socket.
If the server is listening on a pipe or UNIX domain socket, the name is
returned as a string.

### server.close([callback])

Close the server and terminate all clients, calls callback when done.
Expand Down
18 changes: 18 additions & 0 deletions lib/websocket-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,24 @@ class WebSocketServer extends EventEmitter {
this.options = options;
}

/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address () {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}

if (!this._server) return null;
return this._server.address();
}

/**
* Close the server.
*
Expand Down
28 changes: 28 additions & 0 deletions test/websocket-server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,34 @@ describe('WebSocketServer', function () {
});
});

describe('#address', function () {
it('returns the address of the server', function (done) {
const wss = new WebSocket.Server({ port: 0 }, () => {
const addr = wss.address();

assert.deepStrictEqual(addr, wss._server.address());
wss.close(done);
});
});

it('throws an error when operating in "noServer" mode', function () {
const wss = new WebSocket.Server({ noServer: true });

assert.throws(() => {
wss.address();
}, /^Error: The server is operating in "noServer" mode$/);
});

it('returns `null` if called after close', function (done) {
const wss = new WebSocket.Server({ port: 0 }, () => {
wss.close(() => {
assert.strictEqual(wss.address(), null);
done();
});
});
});
});

describe('#close', function () {
it('does not thrown when called twice', function (done) {
const wss = new WebSocket.Server({ port: 0 }, () => {
Expand Down

0 comments on commit 8d61fa0

Please sign in to comment.