+
+ internals.socket.addEventListener('message', internals.onMessage);
+ internals.socket.addEventListener('error', internals.onError);
+ internals.socket.addEventListener('close', internals.onClose);
+ },
+
+ // Handles socket errors.
+
+ onError(event) {
+
+ console.error('Socket error. Closing connection');
+ internals.socket.close();
+ },
+
+ // Handles socket errors.
+
+ onClose(event) {
+
+ console.debug(`Connection closed: ${event.reason || 'Unknown reason'}. Retrying in ${internals.kReconnectInterval}ms`);
+
+ internals.retry && clearTimeout(internals.retry);
+ internals.retry = setTimeout(() => {
+
+ console.debug('Reconnecting socket.');
+ internals.retry = null;
+ internals.connect();
+ }, internals.kReconnectInterval);
+ },
+
+ // Forwards events from the socket to our internal event emitter.
+
+ onMessage(event) {
+
+ internals.eventEmitter.emit('message', event);