web_synchronization_tool/lib/windows/socket_tool.dart

133 lines
2.7 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 'package:web_synchronization_tool/windows/synchronization_web_tool.dart';
2024-04-03 14:36:36 +08:00
import 'little_extension.dart';
import 'code.dart';
import 'number_tool.dart';
2024-04-06 15:38:28 +08:00
class SocketUtils extends SyncSocket{
2024-04-03 14:36:36 +08:00
// 私有构造函数
SocketUtils._();
// 私有静态变量,保存类的唯一实例
static SocketUtils? _instance;
// 公开的静态方法,返回类的唯一实例
static SocketUtils getInstance() {
_instance ??= SocketUtils._();
return _instance!;
}
}
2024-04-06 15:38:28 +08:00
class SyncSocket {
2024-04-03 14:36:36 +08:00
String url = '127.0.0.1';
2024-04-03 14:36:36 +08:00
static int port = 12345;
RawDatagramSocket? socket;
2024-04-03 17:45:52 +08:00
// IC 0主机 1 从机
int ic = 1;
/// 从机ip
List<String> childrenIp = [];
2024-04-03 14:36:36 +08:00
connect() async {
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
2024-04-03 14:36:36 +08:00
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
Map data = dataCute(d.data);
// 收到消息
if (data['op'] == 2){
print(data);
//点击
if (data['click'] != null){
Map click = data['click'];
int x = click['x'] as int;
int y = click['y'] as int;
SynchronizationWebTool.getInstance().clickSynchronization(x, y);
}
//输入
if (data['input'] != null){
int input = data['input'];
List<int> nums = NumberTool().randomNum(input);
SynchronizationWebTool.getInstance().input(nums);
}
}
// 心跳
if (data['op'] == 11){
}
2024-04-03 17:45:52 +08:00
});
2024-04-03 14:36:36 +08:00
}
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 str = cutecode(pData);
Map map = json.decode(str);
return map;
}
}