Move/refactor keepalive logic and add disconnect timer

We now disconnect ourselves if we don't get the server's response to a
keepalive request within 30s. This way we will eventually disconnect if
the network goes away but the socket is not closed.*

* See code.google.com/p/chromium/issues/detail?id=197841 and
https://stackoverflow.com/questions/11755605/chrome-websocket-connection-not-closed-when-browser-closed

We will then try to reconnect once a minute (See 8a10c96);

Keepalives belong at this level anyway, since the format is defined by
both the websocket resource protocol and our specific server url
structure.

// FREEBIE
This commit is contained in:
lilia 2015-07-16 13:16:50 -07:00
parent 8a10c96ab4
commit 7d3d634a2d
6 changed files with 62 additions and 65 deletions

View file

@ -24,7 +24,6 @@
TextSecureWebSocket = function (url) {
'use strict';
var keepAliveTimer;
var reconnectSemaphore = 0;
var reconnectTimeout = 1000;
var socket;
@ -34,27 +33,10 @@ TextSecureWebSocket = function (url) {
onclose : function() {},
onerror : function() {},
getStatus : function() { return socket.readyState; },
close : function() { calledClose = true; }
close : function() { calledClose = true; socket.close(); }
};
var error;
function resetKeepAliveTimer() {
clearTimeout(keepAliveTimer);
if (calledClose) { return; }
keepAliveTimer = setTimeout(function() {
if (socket.readyState === WebSocket.OPEN) {
socket.send(
new textsecure.protobuf.WebSocketMessage({
type: textsecure.protobuf.WebSocketMessage.Type.REQUEST,
request: { verb: 'GET', path: '/v1/keepalive' }
}).encode().toArrayBuffer()
);
}
resetKeepAliveTimer();
}, 55000);
};
function onclose(e) {
if (!error && !calledClose) {
reconnectSemaphore--;
@ -74,22 +56,18 @@ TextSecureWebSocket = function (url) {
function onmessage(response) {
socketWrapper.onmessage(response);
resetKeepAliveTimer();
};
function send(msg) {
resetKeepAliveTimer();
socket.send(msg);
};
function connect() {
clearTimeout(keepAliveTimer);
if (++reconnectSemaphore <= 0) { return; }
if (socket) { socket.close(); }
socket = new WebSocket(url);
socket.onopen = resetKeepAliveTimer;
socket.onerror = onerror
socket.onclose = onclose;
socket.onmessage = onmessage;