Skip to content

Commit

Permalink
fix onclose event when client closes the connection (#360)
Browse files Browse the repository at this point in the history
* fix onclose event when client closes the connection

* fix onclose event when client fails the connection
  • Loading branch information
regseb authored May 24, 2022
1 parent 336eba2 commit caba3e0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/algorithms/close.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,19 @@ export function closeWebSocketConnection(context, code, reason) {
code,
reason
});
const serverCloseEvent = createCloseEvent({
type: 'server::close',
target: context,
code,
reason
});

delay(() => {
networkBridge.removeWebSocket(context, context.url);

context.readyState = WebSocket.CLOSED;
context.dispatchEvent(closeEvent);
context.dispatchEvent(serverCloseEvent);

if (server) {
server.dispatchEvent(closeEvent, server);
Expand All @@ -37,6 +44,13 @@ export function failWebSocketConnection(context, code, reason) {
reason,
wasClean: false
});
const serverCloseEvent = createCloseEvent({
type: 'server::close',
target: context,
code,
reason,
wasClean: false
});

const errorEvent = createEvent({
type: 'error',
Expand All @@ -49,6 +63,7 @@ export function failWebSocketConnection(context, code, reason) {
context.readyState = WebSocket.CLOSED;
context.dispatchEvent(errorEvent);
context.dispatchEvent(closeEvent);
context.dispatchEvent(serverCloseEvent);

if (server) {
server.dispatchEvent(closeEvent, server);
Expand Down
17 changes: 17 additions & 0 deletions tests/functional/websockets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,23 @@ test.cb('that onclose is called after the client closes the connection', t => {
};
});

test.cb('that the server gets called when the client closes the connection', t => {
const testServer = new Server('ws://localhost:8080');

testServer.on('connection', socket => {
socket.onclose = function close(event) {
t.is(event.target.readyState, WebSocket.CLOSED, 'onclose fires as expected');
t.end();
};
});

const mockSocket = new WebSocket('ws://localhost:8080');

mockSocket.onopen = function open() {
mockSocket.close();
};
});

test.cb('that the server gets called when the client sends a message', t => {
const testServer = new Server('ws://localhost:8080');

Expand Down

0 comments on commit caba3e0

Please sign in to comment.