#first commit
This commit is contained in:
54
lib/core/network/tcp/tcp_client.dart
Normal file
54
lib/core/network/tcp/tcp_client.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart';
|
||||
|
||||
class TcpClient {
|
||||
Socket? _socket;
|
||||
final _decoder = ProtocolDecoder();
|
||||
// 使用 StreamController 将原始数据流暴露给外部,以便多个 DataSource 监听
|
||||
final _controller = StreamController<RawPacket>.broadcast();
|
||||
Stream<RawPacket> get packetStream => _controller.stream;
|
||||
|
||||
// 通过参数配置,不硬编码
|
||||
Future<void> connect({required String host, required int port}) async {
|
||||
try {
|
||||
_socket = await Socket.connect(
|
||||
host,
|
||||
port,
|
||||
timeout: const Duration(seconds: 5),
|
||||
);
|
||||
|
||||
_socket!.listen(
|
||||
(data) {
|
||||
var packets = _decoder.decode(data);
|
||||
for (var packet in packets) {
|
||||
_controller.add(packet);
|
||||
}
|
||||
},
|
||||
onDone: disconnect,
|
||||
onError: (e) => disconnect(),
|
||||
);
|
||||
} catch (e) {
|
||||
rethrow; // 向上抛出连接异常
|
||||
}
|
||||
}
|
||||
|
||||
void send(Map<String, dynamic> data) {
|
||||
if (_socket == null) throw Exception("Socket not connected");
|
||||
_socket!.write(jsonEncode(data));
|
||||
}
|
||||
|
||||
void sendRaw(int cmd, List<int> payload) {
|
||||
if (_socket == null) return;
|
||||
// 组装:头 AB AA + 指令 + 数据 + 尾 AA AB
|
||||
final data = [0xAB, 0xAA, cmd, ...payload, 0xAA, 0xAB];
|
||||
_socket!.add(data);
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_socket?.destroy();
|
||||
_socket = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user