Replace ws with uws (#918)

* change to uws (waiting for the next release tho)

* clean up, fix reconnections (maybe)

* change voice to use uws

* so messy
This commit is contained in:
Gus Caplan
2016-11-23 18:30:00 -06:00
committed by Schuyler Cebulskie
parent 32879419e2
commit c91ee7a3e7
3 changed files with 18 additions and 16 deletions

View File

@@ -1,10 +1,9 @@
const browser = typeof window !== 'undefined';
const WebSocket = browser ? window.WebSocket : require('ws'); // eslint-disable-line no-undef
const WebSocket = browser ? window.WebSocket : require('uws'); // eslint-disable-line no-undef
const EventEmitter = require('events').EventEmitter;
const Constants = require('../../util/Constants');
const inflate = browser ? require('zlibjs').inflateSync : require('zlib').inflateSync;
const pako = require('pako');
const PacketManager = require('./packets/WebSocketPacketManager');
const convertArrayBuffer = require('../../util/ConvertArrayBuffer');
/**
* The WebSocket Manager of the Client
@@ -80,11 +79,16 @@ class WebSocketManager extends EventEmitter {
this.normalReady = false;
if (this.status !== Constants.Status.RECONNECTING) this.status = Constants.Status.CONNECTING;
this.ws = new WebSocket(gateway);
if (browser) this.ws.binaryType = 'arraybuffer';
this.ws.onopen = () => this.eventOpen();
if (browser) {
this.ws.binaryType = 'arraybuffer';
this.ws.on('open', this.eventOpen.bind(this));
this.ws.on('error', this.eventError.bind(this));
} else {
this.ws.onopen = () => this.eventOpen();
this.ws.onerror = (e) => this.eventError(e);
}
this.ws.onclose = (d) => this.eventClose(d);
this.ws.onmessage = (e) => this.eventMessage(e);
this.ws.onerror = (e) => this.eventError(e);
this._queue = [];
this._remaining = 3;
}
@@ -230,10 +234,7 @@ class WebSocketManager extends EventEmitter {
* @returns {Object}
*/
parseEventData(data) {
if (typeof data !== 'string') {
if (data instanceof ArrayBuffer) data = convertArrayBuffer(data);
data = inflate(data).toString();
}
if (data instanceof ArrayBuffer) data = pako.inflate(data, { to: 'string' });
return JSON.parse(data);
}
@@ -261,7 +262,7 @@ class WebSocketManager extends EventEmitter {
* @param {Error} error The encountered error
*/
if (this.client.listenerCount('error') > 0) this.client.emit('error', err);
this.ws.close();
this.tryReconnect();
}
_emitReady(normal = true) {
@@ -305,6 +306,7 @@ class WebSocketManager extends EventEmitter {
* Tries to reconnect the client, changing the status to Constants.Status.RECONNECTING.
*/
tryReconnect() {
if (this.status === Constants.Status.RECONNECTING) return;
this.status = Constants.Status.RECONNECTING;
this.ws.close();
this.packetManager.handleQueue();