silphius/app/client/remote.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-07-21 02:57:29 -05:00
import Client from '@/net/client.js';
2024-07-20 21:26:00 -05:00
import {encode} from '@/net/packets/index.js';
2024-07-20 04:41:00 -05:00
import {CLIENT_PREDICTION} from '@/util/constants.js';
2024-07-22 00:13:03 -05:00
import {withResolvers} from '@/util/promise.js';
2024-06-10 22:42:30 -05:00
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(
2024-07-21 02:57:29 -05:00
new URL('./prediction.js', import.meta.url),
2024-06-10 22:42:30 -05:00
{type: 'module'},
);
this.worker.postMessage({host});
this.worker.onmessage = (event) => {
2024-08-06 00:40:43 -05:00
this.throughput.$$down += event.data.byteLength;
2024-06-10 22:42:30 -05:00
this.accept(event.data);
};
}
else {
2024-06-12 23:17:24 -05:00
const url = new URL(`wss://${host}/ws`)
this.socket = new WebSocket(url.href);
2024-06-10 22:42:30 -05:00
this.socket.binaryType = 'arraybuffer';
2024-06-13 12:24:32 -05:00
const onMessage = (event) => {
2024-08-06 00:40:43 -05:00
this.throughput.$$down += event.data.byteLength;
2024-06-10 22:42:30 -05:00
this.accept(event.data);
2024-06-13 12:24:32 -05:00
}
2024-07-22 00:13:03 -05:00
const {promise, resolve} = withResolvers();
2024-06-13 12:24:32 -05:00
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'}));
2024-06-10 22:42:30 -05:00
});
2024-06-13 12:24:32 -05:00
this.accept(encode({type: 'ConnectionStatus', payload: 'connected'}));
2024-06-10 22:42:30 -05:00
}
}
disconnect() {
if (CLIENT_PREDICTION) {
this.worker.terminate();
}
else {
this.socket.close();
}
}
transmit(packed) {
2024-08-06 00:40:43 -05:00
this.throughput.$$up += packed.byteLength;
2024-06-10 22:42:30 -05:00
if (CLIENT_PREDICTION) {
this.worker.postMessage(packed);
}
else {
this.socket.send(packed);
}
}
}