89 lines
2.5 KiB
JavaScript
89 lines
2.5 KiB
JavaScript
import Client from '@/net/client.js';
|
|
import {decode, encode} from '@/net/packets/index.js';
|
|
import {CLIENT_INTERPOLATION, CLIENT_PREDICTION} from '@/util/constants.js';
|
|
|
|
export default class RemoteClient extends Client {
|
|
socket = null;
|
|
interpolator = null;
|
|
predictor = null;
|
|
async connect(host) {
|
|
this.interpolator = new Worker(
|
|
new URL('./interpolator.js', import.meta.url),
|
|
{type: 'module'},
|
|
);
|
|
if (CLIENT_INTERPOLATION) {
|
|
this.interpolator = new Worker(
|
|
new URL('./interpolator.js', import.meta.url),
|
|
{type: 'module'},
|
|
);
|
|
this.interpolator.addEventListener('message', (event) => {
|
|
this.accept(event.data);
|
|
});
|
|
}
|
|
if (CLIENT_PREDICTION) {
|
|
this.predictor = new Worker(
|
|
new URL('./predictor.js', import.meta.url),
|
|
{type: 'module'},
|
|
);
|
|
this.predictor.addEventListener('message', (event) => {
|
|
const [flow, packet] = event.data;
|
|
switch (flow) {
|
|
case 0: {
|
|
const packed = encode(packet);
|
|
this.throughput.$$up += packed.byteLength;
|
|
this.socket.send(packed);
|
|
break;
|
|
}
|
|
case 1: {
|
|
if (CLIENT_INTERPOLATION) {
|
|
this.interpolator.postMessage(packet);
|
|
}
|
|
else {
|
|
this.accept(packet);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
const url = new URL(`wss://${host}/ws`)
|
|
this.socket = new WebSocket(url.href);
|
|
this.socket.binaryType = 'arraybuffer';
|
|
this.socket.addEventListener('message', (event) => {
|
|
this.throughput.$$down += event.data.byteLength;
|
|
const packet = decode(event.data);
|
|
if (CLIENT_PREDICTION) {
|
|
this.predictor.postMessage([1, packet]);
|
|
}
|
|
else if (CLIENT_INTERPOLATION) {
|
|
this.interpolator.postMessage(packet);
|
|
}
|
|
else {
|
|
this.accept(packet);
|
|
}
|
|
});
|
|
this.socket.addEventListener('close', () => {
|
|
this.accept({type: 'ConnectionStatus', payload: 'aborted'});
|
|
});
|
|
this.socket.addEventListener('error', () => {
|
|
this.accept({type: 'ConnectionStatus', payload: 'aborted'});
|
|
});
|
|
this.accept({type: 'ConnectionStatus', payload: 'connected'});
|
|
}
|
|
disconnect() {
|
|
if (CLIENT_INTERPOLATION) {
|
|
this.interpolator.terminate();
|
|
}
|
|
}
|
|
transmit(packet) {
|
|
if (CLIENT_PREDICTION) {
|
|
this.predictor.postMessage([0, packet]);
|
|
}
|
|
else {
|
|
const packed = encode(packet);
|
|
this.throughput.$$up += packed.byteLength;
|
|
this.socket.send(packed);
|
|
}
|
|
}
|
|
}
|