45 lines
1.0 KiB
JavaScript
45 lines
1.0 KiB
JavaScript
import Connection from "./Connection.js";
|
|
|
|
export default class Socket {
|
|
connection;
|
|
disabled = true;
|
|
requestID = 1;
|
|
pending = new Map();
|
|
|
|
constructor() {
|
|
this.connection = new Connection(this.receive);
|
|
}
|
|
|
|
isOpen() {
|
|
if(this.connection.checkOpen()) {
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
send(msg) {
|
|
return new Promise(resolve => {
|
|
const id = (++this.requestID).toString();
|
|
this.pending.set(id, resolve);
|
|
this.connection.send(JSON.stringify({ id, ...msg }));
|
|
});
|
|
}
|
|
|
|
receive = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
if (msg.id && this.pending.has(msg.id)) {
|
|
this.pending.get(msg.id)(msg);
|
|
this.pending.delete(msg.id);
|
|
return;
|
|
} else {
|
|
this.onBroadcast(msg)
|
|
}
|
|
}
|
|
|
|
onBroadcast(msg) {
|
|
window.dispatchEvent(new CustomEvent(msg.event, {
|
|
detail: msg.msg
|
|
}));
|
|
}
|
|
} |