silphius/app/client/prediction.js
2024-07-22 00:13:03 -05:00

35 lines
1016 B
JavaScript

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