silphius/app/net/client/remote.js

58 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-06-10 22:42:30 -05:00
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 {
2024-06-12 23:17:24 -05:00
const url = new URL(`wss://${host}/ws`)
if ('production' === process.env.NODE_ENV) {
url.protocol = 'ws:';
}
this.socket = new WebSocket(url.href);
2024-06-10 22:42:30 -05:00
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);
}
}
}