NDOJ/resources/event.js

77 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
function EventReceiver(websocket, poller, channels, last_msg, onmessage) {
this.websocket_path = websocket;
this.channels = channels;
this.last_msg = last_msg;
this.poller_base = poller;
this.poller_path = poller + channels.join('|');
if (onmessage)
this.onmessage = onmessage;
var receiver = this;
2024-02-05 21:17:37 +00:00
var time_retry = 1000;
2020-01-21 06:35:58 +00:00
function init_poll() {
function long_poll() {
$.ajax({
url: receiver.poller_path,
data: {last: receiver.last_msg},
success: function (data, status, jqXHR) {
receiver.onmessage(data.message);
receiver.last_msg = data.id;
long_poll();
},
error: function (jqXHR, status, error) {
if (jqXHR.status == 504)
long_poll();
else {
console.log('Long poll failure: ' + status);
console.log(jqXHR);
setTimeout(long_poll, 2000);
}
},
dataType: "json"
});
}
long_poll();
}
this.onwsclose = null;
if (window.WebSocket) {
2022-05-18 18:50:18 +00:00
function connect() {
this.websocket = new WebSocket(websocket);
var timeout = setTimeout(function () {
receiver.websocket.close();
receiver.websocket = null;
init_poll();
}, 2000);
this.websocket.onopen = function (event) {
clearTimeout(timeout);
this.send(JSON.stringify({
command: 'start-msg',
start: last_msg
}));
this.send(JSON.stringify({
command: 'set-filter',
filter: channels
}));
};
this.websocket.onmessage = function (event) {
var data = JSON.parse(event.data);
receiver.onmessage(data.message);
receiver.last_msg = data.id;
};
this.websocket.onclose = function (event) {
if (event.code != 1000 && receiver.onwsclose !== null)
receiver.onwsclose(event);
if (event.code == 1006) {
2024-02-05 21:17:37 +00:00
setTimeout(connect, time_retry);
time_retry += 2000;
2022-05-18 18:50:18 +00:00
}
2022-05-18 18:39:20 +00:00
}
2020-01-21 06:35:58 +00:00
}
2022-05-18 18:50:18 +00:00
connect();
2020-01-21 06:35:58 +00:00
} else {
this.websocket = null;
init_poll();
}
}