@hazae41/kcp
Version:
Zero-copy KCP protocol for the web
107 lines (104 loc) • 2.64 kB
JavaScript
import { Bytes } from '@hazae41/bytes';
import { FullDuplex } from '@hazae41/cascade';
import { Cursor } from '@hazae41/cursor';
import { Future } from '@hazae41/future';
import { SecretKcpReader } from './reader.mjs';
import { SecretKcpWriter } from './writer.mjs';
class KcpDuplex {
params;
#secret;
constructor(params = {}) {
this.params = params;
this.#secret = new SecretKcpDuplex(params);
}
[Symbol.dispose]() {
this.close();
}
get conversation() {
return this.#secret.conversation;
}
get inner() {
return this.#secret.inner;
}
get outer() {
return this.#secret.outer;
}
get closing() {
return this.#secret.closing;
}
get closed() {
return this.#secret.closed;
}
error(reason) {
this.#secret.error(reason);
}
close() {
this.#secret.close();
}
}
class SecretKcpDuplex {
params;
duplex;
reader;
writer;
conversation;
resolveOnClose = new Future();
resolveOnError = new Future();
resolveOnAckBySerial = new Map();
sendCounter = 0;
recvCounter = 0;
constructor(params = {}) {
this.params = params;
const { conversation = new Cursor(Bytes.random(4)).readUint32OrThrow(true) } = this.params;
this.conversation = conversation;
this.reader = new SecretKcpReader(this);
this.writer = new SecretKcpWriter(this);
this.duplex = new FullDuplex({
input: {
write: m => this.reader.onWrite(m)
},
output: {
write: m => this.writer.onWrite(m)
},
close: () => this.#onDuplexClose(),
error: e => this.#onDuplexError(e)
});
}
[Symbol.dispose]() {
this.close();
}
get inner() {
return this.duplex.inner;
}
get outer() {
return this.duplex.outer;
}
get input() {
return this.duplex.input;
}
get output() {
return this.duplex.output;
}
get closing() {
return this.duplex.closing;
}
get closed() {
return this.duplex.closed;
}
async #onDuplexClose() {
this.resolveOnClose.resolve();
await this.params.close?.call(undefined);
}
async #onDuplexError(cause) {
this.resolveOnError.resolve(cause);
await this.params.error?.call(undefined, cause);
}
error(reason) {
this.duplex.error(reason);
}
close() {
this.duplex.close();
}
}
export { KcpDuplex, SecretKcpDuplex };
//# sourceMappingURL=stream.mjs.map