bit4sat/web/src/Websocket.js

74 lines
1.5 KiB
JavaScript
Raw Normal View History

import { apiPort } from './api.js';
2019-03-29 18:50:11 +00:00
let singleton = false;
export class WS {
constructor(){
2019-03-29 18:50:11 +00:00
console.log("starting new websocket")
if (singleton && singleton.open) {
return singleton;
}
const endpoint = `ws://localhost:2015/ws/`;
this.conn = new WebSocket(endpoint);
2019-03-29 18:50:11 +00:00
this.conn.onerror = this.onerror();
this.conn.onclose = this.onclose();
this.conn.onmessage = this.onmessage();
this.conn.onopen = this.onopen();
}
send(data) {
this.conn.send(data);
}
onopen(){
let self = this;
return (ev) => {
self.opened = true;
console.log("websocket opened");
}
}
onerror (){
let self = this;
return (ev) => {
console.error(ev);
}
}
onclose () {
let self = this;
let instance = singleton
return (ev) => {
console.warn("websocket closed");
//TODO: restore on prod
//setTimeout(() =>{
//console.log("websocket: trying to reconnect")
//instance = new WS()
//}, 5000)
}
}
onmessage() {
let self = this;
return (ev) => {
let msg = JSON.parse(ev.data);
switch (msg.type) {
2019-03-30 18:42:41 +00:00
case 'hello':
2019-03-29 18:50:11 +00:00
console.log(msg.data);
break;
2019-03-30 18:42:41 +00:00
case 'upload-accepted':
console.log(msg)
break;
2019-03-29 18:50:11 +00:00
}
}
}
}