2022-08-06 16:52:37 +00:00
|
|
|
const socketUrl = window.location.href.replace('http', 'ws') + '/socket';
|
|
|
|
let reconnectAttempts = 0;
|
|
|
|
let ws;
|
|
|
|
|
|
|
|
export async function connect({ onData }) {
|
|
|
|
ws = new WebSocket(socketUrl);
|
|
|
|
|
|
|
|
ws.onmessage = async evt => {
|
2023-02-24 09:07:08 +00:00
|
|
|
const data = JSON.parse(evt.data || '{}');
|
|
|
|
onData(data);
|
2022-08-06 16:52:37 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
ws.onopen = () => {
|
|
|
|
if (reconnectAttempts) {
|
|
|
|
window.location.reload();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
ws.onclose = async () => {
|
|
|
|
console.error(`Websocket closed, trying to reconnect... (#${reconnectAttempts++})`);
|
|
|
|
await new Promise(res => setTimeout(res, reconnectAttempts * 500));
|
|
|
|
await connect({ onData });
|
|
|
|
};
|
|
|
|
|
2023-02-24 09:07:08 +00:00
|
|
|
ws.onerror = err => console.error('Connection error:', err);
|
2022-08-06 16:52:37 +00:00
|
|
|
}
|