web_synchronization_tool/lib/windows/socket_tool.dart

117 lines
2.4 KiB
Dart
Raw Normal View History

2024-04-03 14:36:36 +08:00
import 'dart:async';
import 'dart:convert';
import 'dart:io';
2024-04-03 14:36:36 +08:00
import 'dart:typed_data';
import 'little_extension.dart';
import 'code.dart';
2024-04-03 14:36:36 +08:00
class SocketUtils extends Socket{
// 私有构造函数
SocketUtils._();
// 私有静态变量,保存类的唯一实例
static SocketUtils? _instance;
// 公开的静态方法,返回类的唯一实例
static SocketUtils getInstance() {
_instance ??= SocketUtils._();
return _instance!;
}
}
class Socket {
static String url = '127.0.0.1';
static int port = 12345;
RawDatagramSocket? socket;
2024-04-03 17:45:52 +08:00
// IC 0主机 1 从机
int ic = 1;
2024-04-03 14:36:36 +08:00
connect() async {
2024-04-03 17:45:52 +08:00
socket = await RawDatagramSocket.bind('127.0.0.3', 1);
2024-04-03 14:36:36 +08:00
print('UDP Socket bound to ${socket?.address.address}:${socket?.port}');
2024-04-03 17:45:52 +08:00
// 发送身份包
Map data = {
"op": 0,
"IC": ic
};
socket?.send(dataMake(data), InternetAddress(url), port);
2024-04-03 14:36:36 +08:00
// 监听来自网络的数据包
socket?.listen((RawSocketEvent e) {
Datagram? d = socket?.receive();
if (d == null) return;
2024-04-03 17:45:52 +08:00
print(d.data.toList());
2024-04-03 14:36:36 +08:00
// String message = String.fromCharCodes(d.data).trim();
2024-04-03 17:45:52 +08:00
Map data = dataCute(d.data);
});
2024-04-03 14:36:36 +08:00
}
2024-04-03 14:36:36 +08:00
/// 发送消息
sendMessage(Map data){
2024-04-03 17:45:52 +08:00
Map messageMap = {
"op": 2,
"value": data
};
socket?.send(dataMake(messageMap), InternetAddress(url), port);
2024-04-03 14:36:36 +08:00
}
/// 心跳
heartbeat(){
2024-04-03 17:45:52 +08:00
Timer timer = Timer(const Duration(seconds: 10), () async {
if (socket == null){
// 重连
await connect();
}
2024-04-03 14:36:36 +08:00
Map data = {
"op": 1,
2024-04-03 17:45:52 +08:00
"IC": ic
2024-04-03 14:36:36 +08:00
};
socket?.send(dataMake(data), InternetAddress(url), port);
heartbeat();
});
}
/// 发送数据的处理
List<int> dataMake(Map map){
// 将Map对象转换为JSON字符串
String json = jsonEncode(map);
// 加密
String ps = makecode(json, skey);
// 转成无符号整数数组
Uint8List uinData = Uint8List.fromList(ps.codeUnits);
// 在前面添加 4位 表示长度的小端序
uinData = uinData.toLittle(value: uinData.length);
return uinData.toList();
}
2024-04-03 17:45:52 +08:00
/// 接收数据处理
Map dataCute(Uint8List data){
if (data.length <= 4) return {};
Uint8List pData = data.sublist(4,data.length);
// String ps = String.fromCharCodes(pData);
String str = cutecode(pData);
print(str);
Map map = json.decode(str);
return map;
}
}