Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(net): typed message + RPC channel over the raw socket (T4)

yhhc6465aaa523d
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 96d51a243..0ab4a9c45 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -78,7 +78,11 @@ export { ScreenInfo, ScreenOrientation } from './screen';
// Network
// =============================================================================
-export { GameSocket, WeChatSocket, createSocket, type GameSocketOptions, type SocketReadyState } from './net';
+export {
+ GameSocket, WeChatSocket, createSocket, NetChannel,
+ type GameSocketOptions, type SocketReadyState, type NetTransport,
+ type NetChannelOptions, type MessageHandler, type RequestHandler,
+} from './net';
// =============================================================================
// Platform (base functions only)
diff --git a/sdk/src/net/NetChannel.ts b/sdk/src/net/NetChannel.ts
new file mode 100644
index 000000000..cabfc7f50
--- /dev/null
+++ b/sdk/src/net/NetChannel.ts
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NetChannel.ts
+ * @brief A typed message + request/response layer over a raw socket. The raw
+ * GameSocket / WeChatSocket only move string|ArrayBuffer frames; this
+ * is the single channel that gives them typed events (`on`/`send`) and
+ * RPC (`handle`/`request`) with a small JSON envelope. Transport-
+ * agnostic — anything that can `send` and surface `onMessage` works.
+ */
+
+/** The minimal socket surface NetChannel drives (GameSocket / WeChatSocket fit). */
+export interface NetTransport {
+ send(data: string | ArrayBuffer): void;
+ onMessage: ((data: string | ArrayBuffer) => void) | null;
+}
+
+export type MessageHandler<T = unknown> = (payload: T) => void;
+export type RequestHandler<Req = unknown, Res = unknown> = (payload: Req) => Res | Promise<Res>;
+
+export interface NetChannelOptions {
+ /** Default RPC timeout in ms (0 disables). Default 10000. */
+ requestTimeoutMs?: number;
+}
+
+interface WireEvent { k: 'event'; t: string; d: unknown; }
+interface WireReq { k: 'req'; t: string; id: number; d: unknown; }
+interface WireRes { k: 'res'; id: number; d?: unknown; e?: string; }
+type Wire = WireEvent | WireReq | WireRes;
+
+interface Pending {
+ resolve: (value: unknown) => void;
+ reject: (err: Error) => void;
+ timer: ReturnType<typeof setTimeout> | null;
+}
+
+/**
+ * Typed messaging over a {@link NetTransport}. Claims the transport's
+ * `onMessage` (it is the message router). Events are fire-and-forget; requests
+ * await a matching response by id (or reject on timeout / remote error).
+ * Binary frames are ignored — the envelope is JSON text.
+ */
+export class NetChannel {
+ private readonly transport: NetTransport;
+ private readonly handlers = new Map<string, Set<MessageHandler>>();
+ private readonly requestHandlers = new Map<string, RequestHandler>();
+ private readonly pending = new Map<number, Pending>();
+ private readonly defaultTimeout: number;
+ private nextId = 1;
+
+ constructor(transport: NetTransport, opts: NetChannelOptions = {}) {
+ this.transport = transport;
+ this.defaultTimeout = opts.requestTimeoutMs ?? 10000;
+ transport.onMessage = (data) => this.handleIncoming_(data);
+ }
+
+ /** Subscribe to a typed event. Returns an unsubscribe function. */
+ on<T = unknown>(type: string, handler: MessageHandler<T>): () => void {
+ let set = this.handlers.get(type);
+ if (!set) { set = new Set(); this.handlers.set(type, set); }
+ set.add(handler as MessageHandler);
+ return () => {
+ const s = this.handlers.get(type);
+ if (s) { s.delete(handler as MessageHandler); if (s.size === 0) this.handlers.delete(type); }
+ };
+ }
+
+ /** Fire-and-forget a typed event to the peer. */
+ send<T = unknown>(type: string, payload: T): void {
+ this.send_({ k: 'event', t: type, d: payload });
+ }
+
+ /** Register the single handler that answers `request(type, …)` from the peer.
+ * Returns an unregister function. */
+ handle<Req = unknown, Res = unknown>(type: string, handler: RequestHandler<Req, Res>): () => void {
+ this.requestHandlers.set(type, handler as RequestHandler);
+ return () => {
+ if (this.requestHandlers.get(type) === (handler as RequestHandler)) {
+ this.requestHandlers.delete(type);
+ }
+ };
+ }
+
+ /** Send a request and await the peer's response (rejects on timeout / remote error). */
+ request<Res = unknown, Req = unknown>(type: string, payload: Req, timeoutMs?: number): Promise<Res> {
+ const id = this.nextId++;
+ const limit = timeoutMs ?? this.defaultTimeout;
+ return new Promise<Res>((resolve, reject) => {
+ const timer = limit > 0
+ ? setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`net request "${type}" timed out after ${limit}ms`));
+ }, limit)
+ : null;
+ this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });
+ this.send_({ k: 'req', t: type, id, d: payload });
+ });
+ }
+
+ /** Reject all in-flight requests and drop handlers (call on disconnect). */
+ dispose(reason = 'net channel closed'): void {
+ for (const [, p] of this.pending) {
+ if (p.timer) clearTimeout(p.timer);
+ p.reject(new Error(reason));
+ }
+ this.pending.clear();
+ this.handlers.clear();
+ this.requestHandlers.clear();
+ }
+
+ // -- internals ------------------------------------------------------------
+
+ private send_(wire: Wire): void {
+ this.transport.send(JSON.stringify(wire));
+ }
+
+ private handleIncoming_(data: string | ArrayBuffer): void {
+ if (typeof data !== 'string') return; // JSON-text envelope only
+ let msg: Wire;
+ try { msg = JSON.parse(data) as Wire; } catch { return; }
+ if (!msg || typeof (msg as { k?: unknown }).k !== 'string') return;
+ switch (msg.k) {
+ case 'event': this.dispatchEvent_(msg.t, msg.d); break;
+ case 'req': this.handleRequest_(msg); break;
+ case 'res': this.resolvePending_(msg); break;
+ }
+ }
+
+ private dispatchEvent_(type: string, payload: unknown): void {
+ const set = this.handlers.get(type);
+ if (!set) return;
+ for (const h of [...set]) h(payload);
+ }
+
+ private handleRequest_(msg: WireReq): void {
+ const handler = this.requestHandlers.get(msg.t);
+ if (!handler) {
+ this.send_({ k: 'res', id: msg.id, e: `no request handler for "${msg.t}"` });
+ return;
+ }
+ Promise.resolve()
+ .then(() => handler(msg.d))
+ .then(
+ (result) => this.send_({ k: 'res', id: msg.id, d: result }),
+ (err) => this.send_({ k: 'res', id: msg.id, e: err instanceof Error ? err.message : String(err) }),
+ );
+ }
+
+ private resolvePending_(msg: WireRes): void {
+ const p = this.pending.get(msg.id);
+ if (!p) return;
+ this.pending.delete(msg.id);
+ if (p.timer) clearTimeout(p.timer);
+ if (msg.e !== undefined) p.reject(new Error(msg.e));
+ else p.resolve(msg.d);
+ }
+}
diff --git a/sdk/src/net/index.ts b/sdk/src/net/index.ts
index 7f4557034..e17fc62d3 100644
--- a/sdk/src/net/index.ts
+++ b/sdk/src/net/index.ts
@@ -2,6 +2,13 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export { GameSocket, type GameSocketOptions, type SocketReadyState } from './GameSocket';
export { WeChatSocket } from './WeChatSocket';
+export {
+ NetChannel,
+ type NetTransport,
+ type NetChannelOptions,
+ type MessageHandler,
+ type RequestHandler,
+} from './NetChannel';
import { GameSocket, type GameSocketOptions } from './GameSocket';
import { WeChatSocket } from './WeChatSocket';
diff --git a/sdk/tests/net-channel.test.ts b/sdk/tests/net-channel.test.ts
new file mode 100644
index 000000000..5fede0367
--- /dev/null
+++ b/sdk/tests/net-channel.test.ts
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, vi } from 'vitest';
+import { NetChannel, type NetTransport } from '../src/net/NetChannel';
+
+/** A pair of in-memory transports wired to each other (a.send → b.onMessage). */
+function loopback(): [NetTransport, NetTransport] {
+ const a: NetTransport = { onMessage: null, send: (d) => { b.onMessage?.(d); } };
+ const b: NetTransport = { onMessage: null, send: (d) => { a.onMessage?.(d); } };
+ return [a, b];
+}
+
+/** A transport that captures sent frames and lets the test inject incoming ones. */
+function spyTransport(): NetTransport & { sent: string[]; receive(s: string | ArrayBuffer): void } {
+ const sent: string[] = [];
+ const t: any = {
+ onMessage: null,
+ sent,
+ send: (d: string | ArrayBuffer) => { if (typeof d === 'string') sent.push(d); },
+ receive: (s: string | ArrayBuffer) => t.onMessage?.(s),
+ };
+ return t;
+}
+
+describe('NetChannel events', () => {
+ it('delivers a typed event peer-to-peer', () => {
+ const [ta, tb] = loopback();
+ const a = new NetChannel(ta);
+ const b = new NetChannel(tb);
+ const got: unknown[] = [];
+ b.on<{ x: number }>('ping', (p) => got.push(p));
+ a.send('ping', { x: 7 });
+ expect(got).toEqual([{ x: 7 }]);
+ });
+
+ it('unsubscribe stops delivery; other types unaffected', () => {
+ const [ta, tb] = loopback();
+ const a = new NetChannel(ta);
+ const b = new NetChannel(tb);
+ const hits: number[] = [];
+ const off = b.on<number>('n', (p) => hits.push(p));
+ a.send('n', 1);
+ off();
+ a.send('n', 2);
+ expect(hits).toEqual([1]);
+ });
+
+ it('ignores malformed and binary frames', () => {
+ const t = spyTransport();
+ const ch = new NetChannel(t);
+ const hits: unknown[] = [];
+ ch.on('x', (p) => hits.push(p));
+ t.receive('not json');
+ t.receive(JSON.stringify({ no: 'kind' }));
+ t.receive(new ArrayBuffer(4));
+ t.receive(JSON.stringify({ k: 'event', t: 'x', d: 1 }));
+ expect(hits).toEqual([1]);
+ });
+});
+
+describe('NetChannel request/response', () => {
+ it('resolves a request from the peer handler', async () => {
+ const [ta, tb] = loopback();
+ const client = new NetChannel(ta);
+ const server = new NetChannel(tb);
+ server.handle<{ a: number; b: number }, number>('sum', ({ a, b }) => a + b);
+ await expect(client.request<number>('sum', { a: 2, b: 3 })).resolves.toBe(5);
+ });
+
+ it('awaits an async handler', async () => {
+ const [ta, tb] = loopback();
+ const client = new NetChannel(ta);
+ const server = new NetChannel(tb);
+ server.handle<string, string>('echo', async (s) => `echo:${s}`);
+ await expect(client.request<string>('echo', 'hi')).resolves.toBe('echo:hi');
+ });
+
+ it('rejects when the handler throws (remote error propagates)', async () => {
+ const [ta, tb] = loopback();
+ const client = new NetChannel(ta);
+ const server = new NetChannel(tb);
+ server.handle('boom', () => { throw new Error('kaboom'); });
+ await expect(client.request('boom', null)).rejects.toThrow('kaboom');
+ });
+
+ it('rejects when the peer has no handler for the type', async () => {
+ const [ta, tb] = loopback();
+ const client = new NetChannel(ta);
+ new NetChannel(tb); // peer with no handlers
+ await expect(client.request('missing', null)).rejects.toThrow(/no request handler/);
+ });
+
+ it('times out a request with no response', async () => {
+ vi.useFakeTimers();
+ try {
+ const t = spyTransport(); // nothing ever responds
+ const ch = new NetChannel(t, { requestTimeoutMs: 50 });
+ const p = ch.request('hang', null);
+ const assertion = expect(p).rejects.toThrow(/timed out/);
+ await vi.advanceTimersByTimeAsync(60);
+ await assertion;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('dispose rejects in-flight requests', async () => {
+ const t = spyTransport();
+ const ch = new NetChannel(t, { requestTimeoutMs: 0 });
+ const p = ch.request('x', null);
+ ch.dispose();
+ await expect(p).rejects.toThrow(/closed/);
+ });
+
+ it('concurrent requests resolve to their own responses', async () => {
+ const [ta, tb] = loopback();
+ const client = new NetChannel(ta);
+ const server = new NetChannel(tb);
+ server.handle<number, number>('double', (n) => n * 2);
+ const [r1, r2, r3] = await Promise.all([
+ client.request<number>('double', 1),
+ client.request<number>('double', 2),
+ client.request<number>('double', 3),
+ ]);
+ expect([r1, r2, r3]).toEqual([2, 4, 6]);
+ });
+});