silphius/app/net/client/remote.js
2024-06-10 22:45:09 -05:00

54 lines
1.1 KiB
JavaScript

import {CLIENT_PREDICTION} from '@/constants.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 {
this.socket = new WebSocket(`wss://${host}/ws`);
this.socket.binaryType = 'arraybuffer';
this.socket.onmessage = (event) => {
this.accept(event.data);
};
await new Promise((resolve) => {
this.socket.onopen = resolve;
});
}
}
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);
}
}
}