CyTube/www/js/ws.js

87 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-06-15 04:33:40 +00:00
(function () {
2018-06-19 06:12:00 +00:00
var TYPE_FRAME = 0;
var TYPE_ACK = 1;
2018-06-15 04:33:40 +00:00
function WSShim(ws) {
this._ws = ws;
this._listeners = Object.create(null);
this._ws.onclose = this._onclose.bind(this);
this._ws.onmessage = this._onmessage.bind(this);
this._ws.onerror = this._onerror.bind(this);
2018-06-19 06:12:00 +00:00
this._ackId = 0;
this._pendingAcks = Object.create(null);
2018-06-15 04:33:40 +00:00
}
WSShim.prototype.listeners = function listeners(frame) {
if (!Object.prototype.hasOwnProperty.call(this._listeners, frame)) {
this._listeners[frame] = [];
}
return this._listeners[frame];
};
WSShim.prototype.on = function on(frame, callback) {
this.listeners(frame).push(callback);
};
2018-06-19 06:12:00 +00:00
WSShim.prototype.emit = function emit(frame, payload, ack) {
var message = {
type: TYPE_FRAME,
frame: frame,
payload: payload
};
2018-06-15 04:33:40 +00:00
2018-06-19 06:12:00 +00:00
if (ack && typeof ack === 'function') {
message.ackId = ++this._ackId;
this._pendingAcks[message.ackId] = ack;
}
2018-06-15 04:33:40 +00:00
2018-06-19 06:12:00 +00:00
this._ws.send(JSON.stringify(message));
};
2018-06-15 04:33:40 +00:00
2018-06-19 06:12:00 +00:00
WSShim.prototype._emit = function _emit(frame, payload) {
2018-06-15 04:33:40 +00:00
this.listeners(frame).forEach(function (cb) {
2018-06-19 06:12:00 +00:00
try {
cb(payload);
} catch (error) {
console.error('Error in callback for ' + frame + ': ' + error);
}
2018-06-15 04:33:40 +00:00
});
};
WSShim.prototype._onclose = function _onclose() {
// TODO: reconnect logic
this._emit('disconnect');
};
WSShim.prototype._onmessage = function _onmessage(message) {
try {
2018-06-19 06:12:00 +00:00
var parsed = JSON.parse(message.data);
console.log(parsed);
var type = parsed.type;
var frame = parsed.frame;
var payload = parsed.payload;
var ackId = parsed.ackId;
if (type === TYPE_ACK && ackId in this._pendingAcks) {
this._pendingAcks[ackId](payload);
delete this._pendingAcks[ackId];
} else if (type === TYPE_FRAME) {
this._emit(frame, payload);
}
2018-06-15 04:33:40 +00:00
} catch (error) {
console.error('Unparseable message from server: ' + message);
console.error(error.stack);
return;
}
};
WSShim.prototype._onerror = function _onerror() {
console.error('Dunno how to handle onerror');
};
window.WSShim = WSShim;
})();