Commit 96c48706 authored by Robert Knight's avatar Robert Knight

Fix sending of WebSocket messages enqueued during a disconnection

Any WebSocket messages submitted whilst the WS is disconnected
should be re-sent when the WS reconnects.

This was broken because upon a disconnect, the 'onclose'
event handler first synchronously called reconnect(), resulting
in a new WebSocket instance being created and then set 'socket'
to null. This caused an error in sendMessages() after the 'onopen'
event was triggered.

Fix the problem by not using a null 'socket' var to represent
a disconnected socket. Instead just use the WebSocket's readyState
property.
parent 78cdd379
......@@ -33,6 +33,20 @@ describe('websocket wrapper', function () {
assert.notEqual(fakeSocket, initialSocket);
});
it('should send queued messages after a reconnect', function () {
// simulate WebSocket setup and initial connection
var socket = new Socket('ws://test:1234');
fakeSocket.onopen({});
// simulate abnormal disconnection
fakeSocket.onclose({code: 1006});
// enqueue a message and check that it is sent after the WS reconnects
socket.send({aKey: 'aValue'});
fakeSocket.onopen({});
assert.calledWith(fakeSocket.send, '{"aKey":"aValue"}');
});
it('should not reconnect after a normal disconnection', function () {
var socket = new Socket('ws://test:1234');
socket.close();
......
......@@ -22,7 +22,7 @@ function Socket(url) {
// queue of JSON objects which have not yet been submitted
var messageQueue = [];
// the current WebSocket instance or null if disconnected
// the current WebSocket instance
var socket;
function sendMessages() {
......@@ -58,7 +58,6 @@ function Socket(url) {
connectOperation.retry(new Error(event.reason));
}
}
socket = null;
self.emit('close', event);
};
......@@ -74,10 +73,6 @@ function Socket(url) {
/** Close the underlying WebSocket connection */
this.close = function () {
if (!socket) {
console.error('Socket.close() called before socket was connected');
return;
}
socket.close();
};
......@@ -94,7 +89,7 @@ function Socket(url) {
/** Returns true if the WebSocket is currently connected. */
this.isConnected = function () {
return socket && socket.readyState === WebSocket.OPEN;
return socket.readyState === WebSocket.OPEN;
};
// establish the initial connection
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment