docs: 为核心协议层、服务层与主要页面补充代码注释,修复下载进度计算逻辑
This commit is contained in:
1 parent
7e618adf6c
commit
854f00038c
14 files changed
+244
-28
No files matched your search
@@ -8,25 +8,49 @@ import 'rcon_stream_parser.dart';
|
||||
import '../../core/l10n/strings.dart';
|
||||
|
||||
/// 去除 Minecraft 消息中的颜色/格式码(§ 后跟一个有效字符)。
|
||||
///
|
||||
/// 服务端命令回显常带 `§a`(绿)、`§l`(加粗)等格式符,
|
||||
/// 直接显示在 Flutter 文本里会变成乱码方块,这里统一剥掉。
|
||||
String stripMinecraftCodes(String input) {
|
||||
return input.replaceAll(RegExp(r'\u00a7[0-9A-Fa-fK-ORk-or]'), '');
|
||||
}
|
||||
|
||||
/// RCON 客户端:与 Minecraft 服务端建立长连接,发送控制台命令。
|
||||
///
|
||||
/// 生命周期:
|
||||
/// ```
|
||||
/// connect() → executeCommand(...) × N → disconnect()
|
||||
/// ↑______ 心跳失败自动重连 ______|
|
||||
/// ```
|
||||
///
|
||||
/// 关键设计:
|
||||
/// - **请求配对**:每条命令分配自增 id,响应按 id 找回对应的 Completer;
|
||||
/// - **心跳保活**:每 30 秒发一次 `list`,失败即判定掉线;
|
||||
/// - **指数退避重连**:1s → 2s → 4s … 封顶 60s,最多 10 次。
|
||||
class RconClient {
|
||||
Socket? _socket;
|
||||
|
||||
/// 请求 id 自增计数器,用于把响应和请求配对
|
||||
int _requestId = 0;
|
||||
|
||||
bool _isAuthenticated = false;
|
||||
|
||||
/// 在途请求表:id → 等待响应的 Completer
|
||||
final Map<int, Completer<RconPacket?>> _pendingRequests = {};
|
||||
|
||||
Timer? _heartbeatTimer;
|
||||
Timer? _reconnectTimer;
|
||||
int _reconnectAttempts = 0;
|
||||
static const _maxReconnectAttempts = 10;
|
||||
|
||||
/// 心跳间隔:太短会给服务端造成无谓负担,太长则掉线发现不及时
|
||||
static const _heartbeatInterval = Duration(seconds: 30);
|
||||
|
||||
/// 连接断开 / 重连成功的外部回调,供 UI 层更新状态
|
||||
VoidCallback? onDisconnected;
|
||||
VoidCallback? onReconnected;
|
||||
|
||||
// 缓存连接参数,用于自动重连
|
||||
String? _host;
|
||||
int? _port;
|
||||
String? _password;
|
||||
@@ -34,6 +58,9 @@ class RconClient {
|
||||
|
||||
bool get isConnected => _isAuthenticated && _socket != null;
|
||||
|
||||
/// 建立 TCP 连接并完成 RCON 认证。
|
||||
///
|
||||
/// 返回 true 表示认证成功;抛异常表示网络层连不上。
|
||||
Future<bool> connect(
|
||||
String host,
|
||||
int port,
|
||||
@@ -46,18 +73,22 @@ class RconClient {
|
||||
_autoReconnect = autoReconnect;
|
||||
|
||||
try {
|
||||
// 5 秒超时:避免弱网下界面长时间卡在加载态
|
||||
_socket = await Socket.connect(
|
||||
host,
|
||||
port,
|
||||
timeout: const Duration(seconds: 5),
|
||||
);
|
||||
|
||||
// 绑定解析器:收到完整包后,按 id 唤醒等待中的请求
|
||||
_socket!.transform(RconStreamParser()).listen((parsed) {
|
||||
final completer = _pendingRequests.remove(parsed.id);
|
||||
completer?.complete(parsed);
|
||||
});
|
||||
|
||||
// type=3 为认证包,payload 即密码(明文,故 RCON 必须走内网或 SSH 隧道)
|
||||
final authResponse = await _sendPacket(3, password);
|
||||
// 认证失败时服务端返回 id = -1,这是协议层的约定
|
||||
_isAuthenticated = authResponse != null && authResponse.id != -1;
|
||||
|
||||
if (_isAuthenticated) {
|
||||
@@ -71,14 +102,17 @@ class RconClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行一条控制台命令,返回服务端原文(可能为 null 表示超时)。
|
||||
Future<String?> executeCommand(String command) async {
|
||||
if (!_isAuthenticated || _socket == null) {
|
||||
throw Exception(S.t('RCON 未连接或未认证'));
|
||||
}
|
||||
// type=2 为命令包
|
||||
final response = await _sendPacket(2, command);
|
||||
return response?.payload;
|
||||
}
|
||||
|
||||
/// 主动断开:取消定时器、销毁 socket、清空认证状态。
|
||||
void disconnect() {
|
||||
_heartbeatTimer?.cancel();
|
||||
_reconnectTimer?.cancel();
|
||||
@@ -88,6 +122,7 @@ class RconClient {
|
||||
_isAuthenticated = false;
|
||||
}
|
||||
|
||||
/// 启动心跳:周期性发 `list`(最轻量的命令),失败即视为掉线。
|
||||
void _startHeartbeat() {
|
||||
_heartbeatTimer?.cancel();
|
||||
_heartbeatTimer = Timer.periodic(_heartbeatInterval, (_) async {
|
||||
@@ -99,6 +134,7 @@ class RconClient {
|
||||
});
|
||||
}
|
||||
|
||||
/// 掉线处理:通知 UI,并按指数退避安排重连。
|
||||
void _handleDisconnect() {
|
||||
_heartbeatTimer?.cancel();
|
||||
onDisconnected?.call();
|
||||
@@ -106,6 +142,7 @@ class RconClient {
|
||||
if (!_autoReconnect || _reconnectAttempts >= _maxReconnectAttempts) return;
|
||||
|
||||
_reconnectAttempts++;
|
||||
// 指数退避:2^(n-1) 秒,最长 60 秒;避免服务端刚崩溃时被反复重连打爆
|
||||
final delay = Duration(
|
||||
seconds: min(60, pow(2, _reconnectAttempts - 1).toInt()),
|
||||
);
|
||||
@@ -123,14 +160,17 @@ class RconClient {
|
||||
});
|
||||
}
|
||||
|
||||
/// 发送一个包并等待对应 id 的响应(5 秒超时)。
|
||||
///
|
||||
/// 超时说明连接已不可用,直接销毁连接,由调用方或重连机制重建。
|
||||
Future<RconPacket?> _sendPacket(int type, String payload) async {
|
||||
final id = ++_requestId;
|
||||
final packet = _buildPacket(id, type, payload);
|
||||
final completer = Completer<RconPacket?>();
|
||||
|
||||
|
||||
_pendingRequests[id] = completer;
|
||||
_socket!.add(packet);
|
||||
|
||||
|
||||
return completer.future.timeout(
|
||||
const Duration(seconds: 5),
|
||||
onTimeout: () {
|
||||
@@ -142,6 +182,10 @@ class RconClient {
|
||||
);
|
||||
}
|
||||
|
||||
/// 按协议拼装二进制包(小端序)。
|
||||
///
|
||||
/// 结构:length | id | type | payload | 0x00 0x00
|
||||
/// 其中 length = 4(id) + 4(type) + payload 长度 + 2(结束符)。
|
||||
Uint8List _buildPacket(int id, int type, String payload) {
|
||||
final payloadBytes = utf8.encode(payload);
|
||||
final length = 4 + 4 + payloadBytes.length + 2;
|
||||
@@ -160,6 +204,7 @@ class RconClient {
|
||||
buffer.add(typeData.buffer.asUint8List());
|
||||
|
||||
buffer.add(payloadBytes);
|
||||
// 协议要求以两个 0x00 结尾
|
||||
buffer.add([0, 0]);
|
||||
|
||||
return buffer.toBytes();
|
||||
|
||||
@@ -2,10 +2,24 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// 一条已解析的 RCON 数据包。
|
||||
///
|
||||
/// RCON 协议(Source RCON)线上格式为小端序:
|
||||
/// ```
|
||||
/// [4B 包长 length][4B 请求 id][4B 包类型 type][payload...][2B 结束符 0x00 0x00]
|
||||
/// ```
|
||||
/// 其中 `length` 只统计其后的部分(id + type + payload + 2 字节结束符)。
|
||||
class RconPacket {
|
||||
/// 包体长度(不含开头的 4 字节自身)
|
||||
final int length;
|
||||
|
||||
/// 请求 id,用于把响应与请求配对;认证失败时服务器返回 -1
|
||||
final int id;
|
||||
|
||||
/// 包类型:2=执行命令,3=认证,0=响应
|
||||
final int type;
|
||||
|
||||
/// 解码后的正文(已剔除末尾结束符)
|
||||
final String payload;
|
||||
|
||||
RconPacket({
|
||||
@@ -16,6 +30,14 @@ class RconPacket {
|
||||
});
|
||||
}
|
||||
|
||||
/// 把 TCP 的字节流切分成一条条 [RconPacket]。
|
||||
///
|
||||
/// TCP 是流式协议,一次 `data` 事件可能带来半个包,也可能带来多个包,
|
||||
/// 因此这里维护一个 [BytesBuilder] 缓冲区:
|
||||
/// 1. 新数据追加到缓冲区;
|
||||
/// 2. 循环从头部读 4 字节长度 → 判断缓冲区是否够一整包;
|
||||
/// 3. 不够就 `break` 等下一次数据;够就切出来解析,继续下一个;
|
||||
/// 4. 剩余未消费的尾巴放回缓冲区。
|
||||
class RconStreamParser extends StreamTransformerBase<Uint8List, RconPacket> {
|
||||
@override
|
||||
Stream<RconPacket> bind(Stream<Uint8List> stream) async* {
|
||||
@@ -25,21 +47,26 @@ class RconStreamParser extends StreamTransformerBase<Uint8List, RconPacket> {
|
||||
buffer.add(chunk);
|
||||
var bytes = buffer.toBytes();
|
||||
|
||||
// 至少要有 4 字节才能读出包长
|
||||
while (bytes.length >= 4) {
|
||||
final byteData = ByteData.sublistView(bytes);
|
||||
final packetLength = byteData.getInt32(0, Endian.little);
|
||||
// 整包长度 = 长度字段自身的 4 字节 + 包体长度
|
||||
final totalSize = 4 + packetLength;
|
||||
|
||||
// 半包:等更多数据到达
|
||||
if (bytes.length < totalSize) break;
|
||||
|
||||
final packetBytes = bytes.sublist(4, totalSize);
|
||||
final packetData = ByteData.sublistView(packetBytes);
|
||||
|
||||
// 最小合法包体为 10 字节(id 4 + type 4 + 结束符 2)
|
||||
if (packetBytes.length >= 10) {
|
||||
yield RconPacket(
|
||||
length: packetLength,
|
||||
id: packetData.getInt32(0, Endian.little),
|
||||
type: packetData.getInt32(4, Endian.little),
|
||||
// 去掉末尾 2 字节结束符;allowMalformed 防止服务端发来非 UTF-8 时整条流崩溃
|
||||
payload: utf8.decode(
|
||||
packetBytes.sublist(8, packetBytes.length - 2),
|
||||
allowMalformed: true,
|
||||
@@ -50,6 +77,7 @@ class RconStreamParser extends StreamTransformerBase<Uint8List, RconPacket> {
|
||||
bytes = bytes.sublist(totalSize);
|
||||
}
|
||||
|
||||
// 用剩余未消费的字节重建缓冲区
|
||||
buffer.clear();
|
||||
if (bytes.isNotEmpty) buffer.add(bytes);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user