2018-05-11 12:31:53 +02:00
|
|
|
function Messaging(screen) {
|
|
|
|
var ws = new WebSocket('ws://' + window.location.hostname + '/play/');
|
2019-08-13 13:46:25 +02:00
|
|
|
var debug = getParameters().debug;
|
|
|
|
var doLog = debug != undefined && debug.match(/^(?:1|t(?:rue)?|v(?:rai)?)$/i);
|
2018-05-11 12:31:53 +02:00
|
|
|
var keepAlivePeriod = 20000;
|
|
|
|
var routes = {callbacks: [], children: {}};
|
|
|
|
|
|
|
|
return {
|
|
|
|
addEventListener: addEventListener,
|
|
|
|
send: send,
|
|
|
|
start: start
|
|
|
|
}
|
|
|
|
|
|
|
|
function get(obj, path, write) {
|
|
|
|
write = write || false;
|
|
|
|
if(path.length < 1) {
|
|
|
|
return obj;
|
|
|
|
} else {
|
|
|
|
if(obj.children[path[0]] == undefined && write) {
|
|
|
|
obj.children[path[0]] = {callbacks: [], children: {}};
|
|
|
|
}
|
|
|
|
if(obj.children[path[0]] != undefined) {
|
|
|
|
return get(obj.children[path[0]], path.slice(1), write);
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-13 13:46:25 +02:00
|
|
|
function getParameters() {
|
|
|
|
var o = {};
|
|
|
|
window.location.search.substr(1).split('&').forEach(function(s) {
|
|
|
|
var t = s.split('=');
|
|
|
|
o[t[0]] = t[1];
|
|
|
|
});
|
|
|
|
return o;
|
|
|
|
}
|
|
|
|
|
2018-05-11 12:31:53 +02:00
|
|
|
function addEventListener(path, callback) {
|
|
|
|
var route = get(routes, path, true);
|
|
|
|
route.callbacks.push(callback);
|
|
|
|
}
|
|
|
|
|
|
|
|
function messageListener(event) {
|
|
|
|
var o = JSON.parse(event.data);
|
|
|
|
var path = [];
|
|
|
|
var tmp = o;
|
|
|
|
while(tmp != undefined && tmp.tag != undefined) {
|
|
|
|
path.push(tmp.tag);
|
|
|
|
tmp = tmp.message;
|
|
|
|
}
|
|
|
|
var route = get(routes, path);
|
|
|
|
if(route != undefined && route.callbacks != undefined) {
|
|
|
|
route.callbacks.forEach(function(f) {f(o);});
|
|
|
|
} else {
|
|
|
|
debug.textContent = event.data;
|
|
|
|
}
|
2019-08-13 13:46:25 +02:00
|
|
|
o.direction = 'client < server';
|
|
|
|
log(o);
|
2018-05-11 12:31:53 +02:00
|
|
|
};
|
|
|
|
|
2019-08-13 13:46:25 +02:00
|
|
|
function log(message) {
|
|
|
|
if(doLog) {
|
|
|
|
console.log(message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-11 12:31:53 +02:00
|
|
|
function start() {
|
|
|
|
ping();
|
|
|
|
addEventListener(["Pong"], ping);
|
|
|
|
ws.addEventListener('message', messageListener);
|
|
|
|
}
|
|
|
|
|
|
|
|
function send(o) {
|
|
|
|
ws.send(JSON.stringify(o));
|
2019-08-13 13:46:25 +02:00
|
|
|
o.direction = 'client > server';
|
|
|
|
log(o);
|
2018-05-11 12:31:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function ping() {
|
|
|
|
setTimeout(function() {send({tag: "Ping"});}, keepAlivePeriod);
|
|
|
|
}
|
|
|
|
}
|