@virusonic/react-native-sdk
Version:
126 lines (109 loc) • 3.82 kB
JavaScript
var RelationListener = require('./relation-listener');
function Websocket(uri, onMessageFn) {
this._uri = uri;
this._relationListeners = [];
this._opened = false;
this._onMessageFn = onMessageFn;
this._wsConnection = null;
// this._dataToSend = [];
this._maxTimeReconnect = 4000;
this._maxTimeForConnect = 2000;
this._incrementIntervalOnReconnect = 200;
this._currentReconnectInterval = 0;
this._waitReconnect = false;
}
Websocket.prototype = {
addRelationListener: function (relationListener) {
this._relationListeners.push(relationListener);
},
connect: function () {
var me = this;
me._manuallyClosed = false;
me._open();
},
write: function (msg) {
var data = JSON.stringify(msg, function (key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
});
if (this._wsConnection && this._wsConnection.readyState === 1) {
this._wsConnection.send(data);
} else {
console.log("Can not send data, because no connection with uri =" + this._uri);
throw new Error("Can not send data, because no connection with uri =" + this._uri);
// this._dataToSend.push(data);
}
},
close: function () {
this._manuallyClosed = true;
if (this._wsConnection) {
this._wsConnection.close();
}
},
_open: function () {
var me = this;
me._waitReconnect = false;
if (me._connecting || me._opened || me._manuallyClosed) {
return;
}
me._connecting = true;
me._wsConnection = new WebSocket(this._uri);
const localWs = this._wsConnection;
const closeTimeout = setTimeout(function () {
localWs.close();
}, me._maxTimeForConnect);
this._wsConnection.onopen = function (event) {
clearTimeout(closeTimeout);
if (me._wsConnection === localWs) {
me._connecting = false;
me._opened = true;
me._currentReconnectInterval = 0;
// me._dataToSend.forEach(function (data) {
// me._wsConnection.send(data);
// });
// me._dataToSend = [];
me._relationListeners.forEach(function (rl) {
if (rl.onConnect) {
rl.onConnect(event);
}
});
}
};
this._wsConnection.onmessage = function (event) {
if (me._onMessageFn && me._wsConnection === localWs) {
me._onMessageFn(event.data);
}
};
this._wsConnection.onclose = function (event) {
clearTimeout(closeTimeout);
if (me._wsConnection === localWs) {
me._connecting = false;
me._opened = false;
me._relationListeners.forEach(function (rl) {
if (rl.onDisconnect) {
rl.onDisconnect(event);
}
});
me._tryReconnect();
}
};
},
_tryReconnect() {
const me = this;
if (!me._manuallyClosed && !me._waitReconnect) {
me._waitReconnect = true;
setTimeout(() => {
me._open();
}, me._getReconnectInterval());
}
},
_getReconnectInterval() {
if (this._currentReconnectInterval < this._maxTimeReconnect) {
this._currentReconnectInterval += this._incrementIntervalOnReconnect;
}
return this._currentReconnectInterval;
}
};
module.exports = Websocket;