feat(framework): net Transport 接口 + 测试用 FakeTransport
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import type { Transport } from '../../YouleNexus/assets/framework/net/transport.ts';
|
||||
|
||||
/** 内存 Transport:模拟服务器。用 microtask 队列异步触发回调,贴近真实 WS 时序。 */
|
||||
export class FakeTransport implements Transport {
|
||||
sent: string[] = [];
|
||||
url = '';
|
||||
private openCb?: () => void;
|
||||
private msgCb?: (f: string) => void;
|
||||
private closeCb?: () => void;
|
||||
private pending: Array<() => void> = [];
|
||||
private closed = false;
|
||||
|
||||
connect(url: string): void { this.url = url; this.pending.push(() => this.openCb?.()); }
|
||||
send(frame: string): void { if (!this.closed) this.sent.push(frame); }
|
||||
close(): void { if (this.closed) return; this.closed = true; this.pending.push(() => this.closeCb?.()); }
|
||||
onOpen(cb: () => void): void { this.openCb = cb; }
|
||||
onMessage(cb: (f: string) => void): void { this.msgCb = cb; }
|
||||
onClose(cb: () => void): void { this.closeCb = cb; }
|
||||
|
||||
/** 测试侧:模拟服务器推一帧给客户端。 */
|
||||
serverPush(frame: string): void { if (!this.closed) this.pending.push(() => this.msgCb?.(frame)); }
|
||||
|
||||
/** 冲刷所有挂起回调(解析微任务)。 */
|
||||
async flush(): Promise<void> {
|
||||
while (this.pending.length) { const fn = this.pending.shift()!; fn(); await Promise.resolve(); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user