silphius/app/net/client/remote.js
2024-06-13 13:24:57 -05:00

68 lines
1.8 KiB
JavaScript

import {CLIENT_PREDICTION} from '@/constants.js';
import {encode} from '@/packets/index.js';
import Client from './client.js';
export default class RemoteClient extends Client {
constructor() {
super();
if (CLIENT_PREDICTION) {
this.worker = undefined;
}
else {
this.socket = undefined;
}
}
async connect(host) {
if (CLIENT_PREDICTION) {
this.worker = new Worker(
new URL('../client/prediction.js', import.meta.url),
{type: 'module'},
);
this.worker.postMessage({host});
this.worker.onmessage = (event) => {
this.accept(event.data);
};
}
else {
const url = new URL(`wss://${host}/ws`)
if ('production' === process.env.NODE_ENV) {
url.protocol = 'ws:';
}
this.socket = new WebSocket(url.href);
this.socket.binaryType = 'arraybuffer';
const onMessage = (event) => {
this.accept(event.data);
}
const {promise, resolve} = Promise.withResolvers();
this.socket.addEventListener('open', resolve);
this.socket.addEventListener('error', () => {
this.accept(encode({type: 'ConnectionStatus', payload: 'aborted'}));
});
await promise;
this.socket.removeEventListener('open', resolve);
this.socket.addEventListener('message', onMessage);
this.socket.addEventListener('close', () => {
this.accept(encode({type: 'ConnectionStatus', payload: 'aborted'}));
});
this.accept(encode({type: 'ConnectionStatus', payload: 'connected'}));
}
}
disconnect() {
if (CLIENT_PREDICTION) {
this.worker.terminate();
}
else {
this.socket.close();
}
}
transmit(packed) {
if (CLIENT_PREDICTION) {
this.worker.postMessage(packed);
}
else {
this.socket.send(packed);
}
}
}