silphius/app/client/prediction.js
2024-08-06 00:00:39 -05:00

35 lines
1012 B
JavaScript

import {encode} from '@/net/packets/index.js';
import {withResolvers} from '@/util/promise.js';
let connected = false;
let socket;
const {promise, resolve} = withResolvers();
onmessage = async (event) => {
if (!connected) {
const url = new URL(`wss://${event.data.host}/ws`)
socket = new WebSocket(url.href);
socket.binaryType = 'arraybuffer';
socket.addEventListener('open', resolve);
socket.addEventListener('error', () => {
postMessage(encode({type: 'ConnectionStatus', payload: 'aborted'}));
close();
});
await promise;
socket.removeEventListener('open', resolve);
socket.addEventListener('message', (event) => {
postMessage(event.data);
});
socket.addEventListener('close', () => {
postMessage(encode({type: 'ConnectionStatus', payload: 'aborted'}));
close();
});
postMessage(encode({type: 'ConnectionStatus', payload: 'connected'}));
connected = true;
return;
}
await promise;
socket.send(event.data);
};