Skip to content

Instantly share code, notes, and snippets.

@Kocal
Created November 12, 2017 21:03
Show Gist options
  • Save Kocal/47df42884c5cb68865125bf5a8a7c021 to your computer and use it in GitHub Desktop.
Save Kocal/47df42884c5cb68865125bf5a8a7c021 to your computer and use it in GitHub Desktop.
Non-tested class for Twitch API WebSocket
class TwitchWebSocket {
constructor() {
this.lastPingTimestamp = null;
this.lastPongTimestamp = null;
this.pingInterval = null;
this.pongTimeout = null;
this.init();
}
init() {
this._ws = new WebSocket('wss://pubsub-edge.twitch.tv');
this._ws.onopen = this.onOpen.bind(this);
this._ws.onmessage = this.onMessage.bind(this);
this._ws.onerror = this.onError.bind(this);
this._ws.onclose = this.onClose.bind(this);
}
reconnect() {
console.warn('Reconnecting to server...');
clearInterval(this.pingInterval);
clearTimeout(this.pongTimeout);
this.init();
}
onOpen() {
this.sendPing();
this.pingInterval = setInterval(() => this.sendPing(), 5000 * 60);
}
onMessage(message) {
const data = JSON.parse(message.data);
// console.log(message);
// console.log(data);
switch (data.type) {
case 'PONG':
this._handleMessagePong();
break;
case 'RECONNECT':
this._handleMessageReconnect();
break;
default:
console.log('yo');
}
}
onError(error) {
console.error(error);
}
onClose(msg) {
console.info('Connection closed', msg);
}
send(message) {
this._ws.send(message);
}
sendJson(data) {
this.send(JSON.stringify(data));
}
sendPing() {
console.info('Sending PING...');
this.lastPingTimestamp = +new Date();
this._reconnectIfPongNotReceived();
this.sendJson({
type: 'PING',
});
}
_reconnectIfPongNotReceived() {
this.pongTimeout = setTimeout(() => {
console.error('PONG has not been received!');
this.reconnect();
}, 10 * 1000);
}
_handleMessagePong(data) {
this.lastPongTimestamp = +new Date();
console.info('Received PONG in %fms', this.lastPongTimestamp - this.lastPingTimestamp);
clearTimeout(this.pongTimeout);
}
_handleMessageReconnect() {
const secondsBeforeReboot = 30;
console.warn(`Server is about to restart in ~${secondsBeforeReboot} seconds...`);
setTimeout(() => {
this.reconnect();
}, secondsBeforeReboot * 1000);
}
}
export default TwitchWebSocket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment