102 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-08-22 19:28:22 +02:00
import EventEmitter from "events";
const bus = new EventEmitter();
2020-08-22 19:28:22 +02:00
const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
2020-08-02 20:22:53 +02:00
function connect() {
const socket = new WebSocket(ws_scheme + "://" + window.location.host + "/ws");
2021-01-30 17:50:09 +01:00
function logSubscribeEvent() {
socket.send(
JSON.stringify(
{
room_name: "",
controls: {
type: "subscribe",
value: "gamelog"
}
2020-12-06 17:08:53 +01:00
}
)
);
2021-01-30 17:50:09 +01:00
}
2021-01-30 17:50:09 +01:00
function logUnsubscribeEvent() {
socket.send(
JSON.stringify(
{
room_name: "",
controls: {
type: "unsubscribe",
value: "gamelog"
}
2020-12-06 17:08:53 +01:00
}
)
);
2021-01-30 17:50:09 +01:00
}
2020-12-06 17:08:53 +01:00
2021-01-30 17:50:09 +01:00
function serverStatusSubscribeEvent() {
socket.send(
JSON.stringify(
{
room_name: "",
controls: {
type: "subscribe",
value: "server_status"
}
2020-12-06 17:08:53 +01:00
}
)
);
2021-01-30 17:50:09 +01:00
}
2020-08-22 19:28:22 +02:00
2021-01-30 17:50:09 +01:00
function commandSendEvent(command) {
socket.send(
JSON.stringify(
{
room_name: "",
controls: {
type: "command",
value: command
}
2020-12-06 17:08:53 +01:00
}
)
);
2021-01-30 17:50:09 +01:00
}
function registerEventEmitter() {
bus.on('log subscribe', logSubscribeEvent);
bus.on('log unsubscribe', logUnsubscribeEvent);
bus.on('server status subscribe', serverStatusSubscribeEvent);
bus.on('command send', commandSendEvent);
}
function unregisterEventEmitter() {
bus.off('log subscribe', logSubscribeEvent);
bus.off('log unsubscribe', logUnsubscribeEvent);
bus.off('server status subscribe', serverStatusSubscribeEvent);
bus.off('command send', commandSendEvent);
}
2020-08-22 19:28:22 +02:00
socket.onmessage = e => {
const {room_name, message} = JSON.parse(e.data);
bus.emit(room_name, message);
}
socket.onerror = e => {
socket.close();
}
socket.onclose = e => {
2021-01-30 17:50:09 +01:00
unregisterEventEmitter()
// reconnect after 5 seconds
setTimeout(connect, 5000);
}
2021-01-30 17:50:09 +01:00
socket.onopen = e => {
registerEventEmitter(socket)
}
}
connect();
2020-08-22 19:28:22 +02:00
export default bus;