src/client/websocket/packets/WebSocketPacketManager.js

src/structures/datastore/WebSocketManagerDataStore.js
Added "rough" reconnection attempting
The following however still needs to be done:
1) stop trying after a certain amount of time
2) increasing timeout between each timeout
3) re-evaluate the current method of how reconnecting is handled
internally
This commit is contained in:
hydrabolt
2016-04-19 20:24:23 +01:00
parent da42b422f0
commit acc9c9bf12
5 changed files with 85 additions and 7 deletions

View File

@@ -4,6 +4,7 @@ const WebSocket = require('ws');
const Constants = require('../../util/Constants');
const zlib = require('zlib');
const PacketManager = require('./packets/WebSocketPacketManager');
const WebSocketManagerDataStore = require('../../structures/datastore/WebSocketManagerDataStore');
class WebSocketManager {
@@ -12,9 +13,12 @@ class WebSocketManager {
this.ws = null;
this.packetManager = new PacketManager(this);
this.emittedReady = false;
this.store = new WebSocketManagerDataStore();
this.reconnecting = false;
}
connect(gateway) {
this.store.gateway = gateway;
gateway += `/?v=${this.client.options.protocol_version}`;
this.ws = new WebSocket(gateway);
this.ws.onopen = () => this.EventOpen();
@@ -24,10 +28,34 @@ class WebSocketManager {
}
send(data) {
this.ws.send(JSON.stringify(data));
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
EventOpen() {
if (this.reconnecting) {
this._sendResume();
} else {
this._sendNewIdentify();
}
}
_sendResume() {
let payload = {
token: this.client.store.token,
session_id: this.store.sessionID,
seq: this.store.sequence,
};
this.send({
op: Constants.OPCodes.RESUME,
d: payload,
});
}
_sendNewIdentify() {
this.reconnecting = false;
let payload = this.client.options.ws;
payload.token = this.client.store.token;
@@ -38,7 +66,9 @@ class WebSocketManager {
}
EventClose() {
if (!this.reconnecting) {
this.tryReconnect();
}
}
EventMessage(event) {
@@ -57,7 +87,7 @@ class WebSocketManager {
}
EventError(e) {
this.tryReconnect();
}
checkIfReady() {
@@ -75,6 +105,15 @@ class WebSocketManager {
}
}
}
tryReconnect() {
this.reconnecting = true;
this.ws.close();
this.packetManager.handleQueue();
this.client.emit(Constants.Events.RECONNECTING);
this.emittedReady = false;
this.connect(this.store.gateway);
}
}
module.exports = WebSocketManager;