You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
2.1 KiB
JavaScript
93 lines
2.1 KiB
JavaScript
5 years ago
|
// Copyright 2020 Thomas Hintz
|
||
|
//
|
||
|
// This file is part of the Alpha Centauri Farming project.
|
||
|
//
|
||
|
// The Alpha Centauri Farming project is free software: you can
|
||
|
// redistribute it and/or modify it under the terms of the GNU General
|
||
|
// Public License as published by the Free Software Foundation, either
|
||
|
// version 3 of the License, or (at your option) any later version.
|
||
|
//
|
||
|
// The Alpha Centauri Farming project is distributed in the hope that
|
||
|
// it will be useful, but WITHOUT ANY WARRANTY; without even the
|
||
|
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
|
||
|
// PURPOSE. See the GNU General Public License for more details.
|
||
|
//
|
||
|
// You should have received a copy of the GNU General Public License
|
||
|
// along with the Alpha Centauri Farming project. If not, see
|
||
|
// <https://www.gnu.org/licenses/>.
|
||
|
|
||
|
export { sendCommand, setMainOnMessage, setSecondaryOnMessage,
|
||
|
setMainOnOpen, openMain, openSecondary,
|
||
|
closeMain, closeSecondary }
|
||
|
|
||
|
class WebSocketConnection {
|
||
|
location = '';
|
||
|
reopen = true;
|
||
|
ws = null;
|
||
|
|
||
|
constructor(location) {
|
||
|
this.location = location;
|
||
|
const loc = window.location;
|
||
|
let uri = '';
|
||
|
if (loc.protocol === "https:") {
|
||
|
uri = "wss:";
|
||
|
} else {
|
||
|
uri = "ws:";
|
||
|
}
|
||
|
uri += "//" + loc.host;
|
||
|
this.ws = new WebSocket(uri + '/websocket/' + location);
|
||
|
}
|
||
|
|
||
|
close() {
|
||
|
this.reopen = false;
|
||
|
this.ws.close();
|
||
|
}
|
||
|
|
||
|
sendCommand(cmd) {
|
||
|
this.ws.send(JSON.stringify(cmd));
|
||
|
}
|
||
|
|
||
|
onmessage(proc) {
|
||
|
this.ws.onmessage = proc;
|
||
|
}
|
||
|
|
||
|
onopen(proc) {
|
||
|
this.ws.onopen = proc;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var ws;
|
||
|
var ws2;
|
||
|
|
||
|
function openMain(location) {
|
||
|
ws = new WebSocketConnection(location);
|
||
|
}
|
||
|
|
||
|
function openSecondary(location) {
|
||
|
ws2 = new WebSocketConnection(location);
|
||
|
}
|
||
|
|
||
|
function closeMain() {
|
||
|
ws.close();
|
||
|
}
|
||
|
|
||
|
function closeSecondary() {
|
||
|
ws2.close();
|
||
|
}
|
||
|
|
||
|
function sendCommand(cmd) {
|
||
|
ws.sendCommand(cmd);
|
||
|
}
|
||
|
|
||
|
function setMainOnMessage(proc) {
|
||
|
ws.onmessage(proc);
|
||
|
}
|
||
|
|
||
|
function setSecondaryOnMessage(proc) {
|
||
|
ws2.onmessage(proc);
|
||
|
}
|
||
|
|
||
|
function setMainOnOpen(proc) {
|
||
|
ws.onopen(proc);
|
||
|
}
|