capybara/frontend/src/Connection.js

41 lines
1,012 B
JavaScript
Raw Normal View History

import Logger from "./common/Logger";
class Connection {
constructor(url) {
this.ws = null;
this.log = Logger(["Connection"], ["log"]).log;
this.messageLog = Logger(["Connection", "Message"], ["log"]).log;
this.url = url;
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onerror = (e) => this.log("Error", e);
this.ws.onopen = () => {
this.log("Open");
};
this.ws.onclose = () => {
this.log("Closed - attempting to reconnect in 4000ms");
setTimeout(() => this.connect(), 4000);
}
}
sendMessage(code, params=[]) {
let message = code;
params.forEach((param, i) => {
if (i == params.length - 1)
message += param;
else
message += param + ";";
});
this.ws.send(message);
return message;
}
disconnect() {
this.ws.close();
}
}
export default Connection;