silphius/app/client/remote.js
2024-08-30 04:29:28 -05:00

38 lines
1.2 KiB
JavaScript

import Client from '@/net/client.js';
import {decode, encode} from '@/net/packets/index.js';
export default class RemoteClient extends Client {
socket = null;
interpolator = null;
async connect(host) {
this.interpolator = new Worker(
new URL('./interpolator.js', import.meta.url),
{type: 'module'},
);
this.interpolator.addEventListener('message', (event) => {
this.accept(event.data);
});
const url = new URL(`wss://${host}/ws`)
this.socket = new WebSocket(url.href);
this.socket.binaryType = 'arraybuffer';
this.socket.addEventListener('message', (event) => {
this.interpolator.postMessage(decode(event.data));
});
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() {
this.interpolator.terminate();
}
transmit(packet) {
const packed = encode(packet);
this.throughput.$$up += packed.byteLength;
this.socket.send(packed);
}
}