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.
40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
2 years ago
|
import ReconnectingWebSocket from 'reconnecting-websocket';
|
||
4 years ago
|
|
||
|
export default class Sock {
|
||
2 years ago
|
private sock: ReconnectingWebSocket;
|
||
|
constructor(public url: string) {
|
||
2 years ago
|
const i = new URL(url, window.location.href);
|
||
2 years ago
|
if (i.host !== window.location.host) i.searchParams.append('sid', document.cookie.split('sid=')[1].split(';')[0]);
|
||
2 years ago
|
i.protocol = i.protocol.replace('http', 'ws');
|
||
|
this.url = i.toString();
|
||
|
this.sock = new ReconnectingWebSocket(this.url);
|
||
|
this.sock.onopen = () => {
|
||
|
console.log('Connected');
|
||
|
this.onopen?.(this.sock);
|
||
|
};
|
||
4 years ago
|
this.sock.onclose = ({ code, reason }) => {
|
||
|
console.warn('Connection closed, ', code, reason);
|
||
2 years ago
|
if (code >= 4000) this.close();
|
||
2 years ago
|
this.onclose?.(code, reason);
|
||
4 years ago
|
};
|
||
|
this.sock.onmessage = (message) => {
|
||
|
if (process.env.NODE_ENV !== 'production') console.log('Sock.onmessage: ', message);
|
||
|
const msg = JSON.parse(message.data);
|
||
2 years ago
|
if (msg.error === 'PermissionError' || msg.error === 'PrivilegeError') this.close();
|
||
|
else this.onmessage?.(message);
|
||
3 years ago
|
};
|
||
|
}
|
||
|
|
||
2 years ago
|
onmessage: (message: MessageEvent<any>) => void;
|
||
|
onclose: (code: number, reason: string) => void;
|
||
|
onopen: (sock: ReconnectingWebSocket) => void;
|
||
|
|
||
4 years ago
|
send(data) {
|
||
2 years ago
|
this.sock.send(data);
|
||
4 years ago
|
}
|
||
|
|
||
|
close() {
|
||
2 years ago
|
this.sock?.close?.();
|
||
4 years ago
|
}
|
||
|
}
|