You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.1 KiB
JavaScript
39 lines
1.1 KiB
JavaScript
import ReconnectingWebSocket from 'reconnecting-websocket';
|
|
|
|
export default class Sock {
|
|
constructor(url) {
|
|
const i = new URL(url, window.location.href);
|
|
i.protocol = i.protocol.replace('http', 'ws');
|
|
this.url = i.toString();
|
|
this.closed = false;
|
|
this.sock = new ReconnectingWebSocket(this.url);
|
|
this.sock.onopen = () => {
|
|
console.log('Connected');
|
|
this.onopen?.(this.sock);
|
|
};
|
|
this.sock.onclose = ({ code, reason }) => {
|
|
console.warn('Connection closed, ', code, reason);
|
|
if (code >= 4000) this.closed = true;
|
|
this.onclose?.(code, reason);
|
|
};
|
|
this.sock.onmessage = (message) => {
|
|
if (process.env.NODE_ENV !== 'production') console.log('Sock.onmessage: ', message);
|
|
const msg = JSON.parse(message.data);
|
|
if (msg.event === 'auth') {
|
|
if (msg.error === 'PermissionError' || msg.error === 'PrivilegeError') {
|
|
this.close();
|
|
}
|
|
} else this.onmessage?.(message);
|
|
};
|
|
}
|
|
|
|
send(data) {
|
|
this.sock.send(data);
|
|
}
|
|
|
|
close() {
|
|
this.closed = true;
|
|
this.sock?.close?.();
|
|
}
|
|
}
|