9.1 远程连接与协议
远端与编辑器之间的消息是「长度前缀 + 正文」的帧:正文以竖线分隔类型、序号与载荷,载荷里的竖线原样保留。流式读取时帧可能被拆成多段到达,重组器按长度前缀切出完整帧;握手用 hello/ack 两步确认两端就绪。
远程调试连接状态
下图给出面向完整编辑器的集成设计。正文中的单节示例验证其中的局部机制,图中的跨模块路径属于集成验收范围。
flowchart TD
A["断开"] --> B["建立连接并协商协议"]
B --> C{"版本与会话检查通过?"}
C -->|否| A
C -->|是| D["同步目标状态"]
D --> E["收发调试命令和事件"]
E -->|超时或断线| F["清理待处理请求"]
F --> A
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 网络 | 《游戏引擎实现原理》 网络章 | 引擎网络管玩法同步;本节管编辑器与设备的调试通道 |
| 远程调试 | 本卷 9.2 | 9.2 建立会话;本节先把消息收发做对 |
| 全卷脉络 | 本卷目录 | 本节是远程调试章的第一块 |
从零实现:远程连接与协议
编码时先拼正文,再在正文前写正文长度。解码先读长度、校验正文实际长度,再从正文里找前两个竖线切出类型与序号,剩余部分整体作为载荷——因此载荷可以包含任意竖线。重组器缓存未完整的数据,循环切帧直到不足一帧。握手状态机只允许 idle → hello-sent → ready。
协议与宿主的职责
Godot 的远程调试可在编辑器检查运行中的项目。helio 的分帧示例接收 JavaScript 字符串,长度前缀按 UTF-16 代码单元计算。若底层按字节分帧,双方需要统一编码和字节计数,并限制最大帧长。图中的连接、状态同步和断线清理由宿主负责。 Godot 调试工具
可运行产物:6 条用例
下面是 src/remote-protocol.ts,层级 L1,完整可编译。运行命令 node --test test/09-1-remote-connection-protocol.test.ts:
// file: src/remote-protocol.ts
// tier: L1
// verify: node --test test/09-1-remote-connection-protocol.test.ts
//
// 卷四(第九章):远程调试——连接与协议。
// 远端与编辑器之间的消息是「长度前缀 + 正文」的帧:正文以 | 分隔类型、
// 序号与载荷(载荷里的 | 原样保留)。流式读取时帧可能被拆成多段到达,
// 重组器按长度前缀切出完整帧;握手用 hello/ack 两步确认两端就绪。
export interface Frame {
type: string;
seq: number;
payload: string;
}
export function encodeFrame(frame: Frame): string {
const body = `${frame.type}|${frame.seq}|${frame.payload}`;
return `${body.length}:${body}`;
}
export function decodeFrame(text: string): Frame {
const colon = text.indexOf(':');
if (colon < 0) throw new Error('缺少长度前缀');
const length = Number(text.slice(0, colon));
const body = text.slice(colon + 1);
if (!Number.isInteger(length) || body.length !== length) {
throw new Error('帧长度不匹配');
}
const firstBar = body.indexOf('|');
const secondBar = body.indexOf('|', firstBar + 1);
if (firstBar < 0 || secondBar < 0) throw new Error('帧正文格式错误');
const type = body.slice(0, firstBar);
const seq = Number(body.slice(firstBar + 1, secondBar));
if (!type || !Number.isInteger(seq)) throw new Error('帧正文格式错误');
return { type, seq, payload: body.slice(secondBar + 1) };
}
export class FrameAssembler {
#buffer = '';
push(chunk: string): Frame[] {
this.#buffer += chunk;
const frames: Frame[] = [];
while (true) {
const colon = this.#buffer.indexOf(':');
if (colon < 0) break;
const length = Number(this.#buffer.slice(0, colon));
if (!Number.isInteger(length) || length < 0) {
throw new Error('缺少长度前缀');
}
const total = colon + 1 + length;
if (this.#buffer.length < total) break;
const body = this.#buffer.slice(colon + 1, total);
frames.push(decodeFrame(`${length}:${body}`));
this.#buffer = this.#buffer.slice(total);
}
return frames;
}
pending(): number {
return this.#buffer.length;
}
}
export class Handshake {
#state: 'idle' | 'hello-sent' | 'ready' = 'idle';
hello(): string {
if (this.#state !== 'idle') throw new Error('握手状态非法');
this.#state = 'hello-sent';
return 'hello';
}
ack(seq: number): void {
if (this.#state !== 'hello-sent') throw new Error('握手状态非法');
if (seq !== 1) throw new Error('握手序号不匹配');
this.#state = 'ready';
}
state(): string {
return this.#state;
}
}
长度前缀是流式协议的第一课:没有它,接收方无法判断一条消息在哪里结束。重组器把「缓存 + 循环切帧」封装起来,调用方每次只管把收到的块丢进去。握手单独建模,是为了拒绝乱序的 ack 和重复的 hello。
下面是 test/09-1-remote-connection-protocol.test.ts,层级 L1:
// file: test/09-1-remote-connection-protocol.test.ts
// tier: L1
// verify: node --test test/09-1-remote-connection-protocol.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { encodeFrame, decodeFrame, FrameAssembler, Handshake } from '../src/remote-protocol.ts';
test('帧编码解码往返', () => {
const frame = { type: 'console', seq: 7, payload: 'hello|world' };
assert.deepEqual(decodeFrame(encodeFrame(frame)), frame);
});
test('长度为前缀且正文长度匹配', () => {
const encoded = encodeFrame({ type: 'ping', seq: 1, payload: '' });
assert.equal(encoded, '7:ping|1|');
});
test('坏帧被拒绝', () => {
assert.throws(() => decodeFrame('abc'), /缺少长度前缀/);
assert.throws(() => decodeFrame('10:ping|1|'), /帧长度不匹配/);
assert.throws(() => decodeFrame('2:xx'), /帧正文格式错误/);
});
test('分片到达后重组出完整帧', () => {
const assembler = new FrameAssembler();
const text = encodeFrame({ type: 'log', seq: 2, payload: 'abcdef' });
const cut = Math.floor(text.length / 2);
assert.deepEqual(assembler.push(text.slice(0, cut)), []);
assert.ok(assembler.pending() > 0);
assert.deepEqual(assembler.push(text.slice(cut)), [{ type: 'log', seq: 2, payload: 'abcdef' }]);
assert.equal(assembler.pending(), 0);
});
test('一次到达多帧全部取出', () => {
const assembler = new FrameAssembler();
const text =
encodeFrame({ type: 'a', seq: 1, payload: '' }) +
encodeFrame({ type: 'b', seq: 2, payload: 'x' });
const frames = assembler.push(text);
assert.deepEqual(frames.map((f) => f.type), ['a', 'b']);
});
test('握手状态按 hello/ack 转移', () => {
const h = new Handshake();
assert.equal(h.state(), 'idle');
assert.equal(h.hello(), 'hello');
assert.throws(() => h.ack(2), /握手序号不匹配/);
h.ack(1);
assert.equal(h.state(), 'ready');
assert.throws(() => h.hello(), /握手状态非法/);
});
本机实测(Node v26.5.0,node --test test/09-1-remote-connection-protocol.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。
前两条钉编解码往返与长度;第三条钉坏帧;第四条钉分片重组;后两条钉多帧与握手状态。
小结
- 流式消息必须有长度前缀,接收方才能切帧。
- 载荷可以包含分隔符,切分只认前两个。
- 重组器缓存半帧,循环输出完整帧。
- 握手是显式状态机,乱序消息直接拒绝。
阅读导航:上一节:8.3 事件标记与性能标注 · 下一节:9.2 真机预览与远程控制 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。