Skip to content

Commit 474c77f

Browse files
fix(Socket): prevent sockets from leaking (obs-websocket-community-projects#191)
Closes obs-websocket-community-projects#188
1 parent adeb28e commit 474c77f

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/Socket.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,16 @@ class Socket extends EventEmitter {
2323
args = args || {};
2424
const address = args.address || 'localhost:4444';
2525

26-
if (this._connected) {
27-
this._socket.close();
26+
if (this._socket) {
27+
try {
28+
// Blindly try to close the socket.
29+
// Don't care if its already closed.
30+
// We just don't want any sockets to leak.
31+
this._socket.close();
32+
} catch (error) {
33+
// These errors are probably safe to ignore, but debug log them just in case.
34+
debug('Failed to close previous WebSocket:', error.message);
35+
}
2836
}
2937

3038
// eslint-disable-next-line no-async-promise-executor

test/auth.spec.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const test = require('ava');
22
const env = require('./setup/environment');
33
const OBSWebSocket = require('..');
44
const SHA256 = require('sha.js/sha256');
5+
const WebSocket = require('ws');
56

67
let unauthServer;
78
let authServer;
@@ -227,3 +228,23 @@ test('closes an existing connection when `connect` is called again', async t =>
227228

228229
t.true(open);
229230
});
231+
232+
test('closes in-flight sockets when `connect` is called', async t => {
233+
const obs = new OBSWebSocket();
234+
obs._connected = false;
235+
236+
// A minimal stub of a socket that is currently connecting.
237+
let closeCalled = 0;
238+
obs._socket = {
239+
readyState: WebSocket.CONNECTING,
240+
close() {
241+
closeCalled++;
242+
}
243+
};
244+
245+
await t.notThrowsAsync(obs.connect({
246+
address: 'localhost:4444'
247+
}));
248+
249+
t.is(closeCalled, 1);
250+
});

0 commit comments

Comments
 (0)