feat(framework): Cocos/浏览器 WebSocket Transport adapter
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import type { Transport } from './transport.ts';
|
||||
|
||||
/** 生产用 Transport:包装运行时全局 WebSocket(Cocos 原生/浏览器)。docs/protocol/01 §2。 */
|
||||
export class CocosWebSocketTransport implements Transport {
|
||||
private ws: WebSocket | null = null;
|
||||
private openCb?: () => void;
|
||||
private msgCb?: (frame: string) => void;
|
||||
private closeCb?: () => void;
|
||||
|
||||
connect(url: string): void {
|
||||
const ws = new WebSocket(url); // url 形如 ws://ip:port
|
||||
this.ws = ws;
|
||||
ws.onopen = () => this.openCb?.();
|
||||
ws.onmessage = (ev: MessageEvent) => this.msgCb?.(typeof ev.data === 'string' ? ev.data : String(ev.data));
|
||||
ws.onclose = () => this.closeCb?.();
|
||||
ws.onerror = () => { try { ws.close(); } catch { /* ignore */ } };
|
||||
}
|
||||
send(frame: string): void { this.ws?.send(frame); }
|
||||
close(): void { try { this.ws?.close(); } catch { /* ignore */ } }
|
||||
onOpen(cb: () => void): void { this.openCb = cb; }
|
||||
onMessage(cb: (frame: string) => void): void { this.msgCb = cb; }
|
||||
onClose(cb: () => void): void { this.closeCb = cb; }
|
||||
}
|
||||
Reference in New Issue
Block a user