123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- class Server {
- constructor(apiDataUrl, websocketUrl) {
- this.socketHandlers = [];
- this.apidataurl = apiDataUrl;
- this.websocketurl = websocketUrl;
- this.webSocket = null;
- }
- apiGet = (path) => {
- return new Promise((resolve, reject) => {
- var r = new XMLHttpRequest();
- r.open("GET", this.apidataurl + path, true);
- r.onreadystatechange = function (response) {
- if (r.readyState == 4 && r.status == 200) {
- resolve(JSON.parse(r.responseText));
- }
- if (r.readyState == 4 && r.status != 200) {
- reject(JSON.parse(r.response));
- }
- return;
- }
- r.onerror = function (response) {
- console.error("onerror", response, r);
- reject(r.responseText);
- }
- r.setRequestHeader("Content-Type", "application/json");
- r.send();
- });
- };
- apiPost = (path, data) => {
- return new Promise((resolve, reject) => {
- var r = new XMLHttpRequest();
- r.open("POST", this.apidataurl + path, true);
- r.onreadystatechange = function (response) {
- if (r.readyState == 4 && r.status == 200) {
- resolve(JSON.parse(r.responseText));
- }
- if (r.readyState == 4 && r.status != 200) {
- reject(r.responseText);
- }
- return;
- }
- r.onerror = function (response) {
- console.error("onerror", response, r);
- reject(r.responseText);
- }
- r.setRequestHeader("Content-Type", "application/json");
- let jsonData = JSON.stringify(data);
- r.send(jsonData);
- });
- };
- websocketConnect = () => {
- this.webSocket = new WebSocket(this.websocketurl);
- this.webSocket.onmessage = this.handleWebsocketMessage;
- this.webSocket.onopen = this.handleWebsocketOpen;
- this.webSocket.onclose = this.handleWebsocketClose;
- this.webSocket.onerror = this.handleWebsocketError;
- };
- websocketSend = (message) => {
- try {
- this.ebSocket.send(message);
- } catch (error) {
- console.error("websocket", error);
- }
- };
- attachWebsocketHandler = (handler) => {
- this.socketHandlers.push(handler);
- }
- removeWebsocketHandler = (handler) => {
- this.socketHandlers.splice(this.socketHandlers.indexOf(handler), 1);
- }
- handleWebsocketMessage = (event) => {
- this.socketHandlers.forEach(handler => {
- if(handler.hasOwnProperty("onmessage")){
- handler.onmessage(event.data);
- }
- })
- }
- handleWebsocketOpen = (event) => {
- this.socketHandlers.forEach(handler => {
- if(handler.hasOwnProperty("onopen")){
- handler.onopen(event);
- }
- })
- }
- handleWebsocketClose = (event) => {
- this.socketHandlers.forEach(handler => {
- if(handler.hasOwnProperty("onclose")){
- handler.onclose(event);
- }
- })
- }
- handleWebsocketError = (event) => {
- this.socketHandlers.forEach(handler => {
- if(handler.hasOwnProperty("onerror")){
- handler.onerror(event);
- }
- })
- }
- }
|