部分优化提交

This commit is contained in:
Daisy 2024-04-01 11:04:34 +08:00
parent 9f5d5b21a5
commit 2db8ce5166

View File

@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:io';
@ -7,24 +6,28 @@ import 'package:star_lock/talk/udp/udp_reciverData.dart';
import '../../blue/io_tool/io_model.dart';
import '../../blue/io_tool/manager_event_bus.dart';
class UDPManage{
class UDPManage {
static UDPManage? _manager;
UDPManage._init() {
initUdp();
_streamSubscription = EventBusManager().eventBus!.on<EventSendModel>().listen((EventSendModel sendModel) {
_streamSubscription = EventBusManager()
.eventBus!
.on<EventSendModel>()
.listen((EventSendModel sendModel) {
// print("sendModel.sendChannel:${sendModel.sendChannel}");
if(sendModel.sendChannel == DataChannel.udp){
if (sendModel.sendChannel == DataChannel.udp) {
List<int> data = sendModel.data;
sendData(data);
}
});
}
static UDPManage _share(){
static UDPManage _share() {
_manager ??= UDPManage._init();
return _manager!;
}
factory UDPManage() => _share();
UDPManage get manager => _share();
@ -35,7 +38,7 @@ class UDPManage{
// String? _mIp = '';
String host = '';
int port = 0;
String lockId = '';// id id来判断是哪把锁发对讲过来
String lockId = ''; // id id来判断是哪把锁发对讲过来
void initUdp() async {
var listAddress = InternetAddress.lookup(host!);
@ -49,25 +52,26 @@ class UDPManage{
}
Future<Null> _initUdp() async {
if(port == 0){
if (port == 0) {
print('❌ Udp ----> _port == 0');
return;
}
print('Udp ----> host:$host port:$port');
var addressIListenFrom = InternetAddress.anyIPv4;
int portIListenOn = 62288;
RawDatagramSocket.bind(addressIListenFrom, portIListenOn).then((RawDatagramSocket socket){
RawDatagramSocket.bind(addressIListenFrom, portIListenOn)
.then((RawDatagramSocket socket) {
_udpSocket = socket;
///广
_udpSocket!.broadcastEnabled = true;
_onReceiveData(socket);
});
}
void _onReceiveData(RawDatagramSocket socket) {
socket.listen((RawSocketEvent event) {
if(event == RawSocketEvent.read){
if (event == RawSocketEvent.read) {
Datagram? dg = socket.receive();
try {
// print('Did received data on the stream (length --> ${dg!.data.length}) dg!.data:${dg!.data}');
@ -81,8 +85,8 @@ class UDPManage{
}
void sendData(List<int> data) {
if(null == _udpSocket || null == data || data.isEmpty || host == ''){
if(null == _udpSocket ){
if (null == _udpSocket || null == data || data.isEmpty || host == '') {
if (null == _udpSocket) {
print('❌ Udp ----> null == _udpSocket');
initUdp();
}
@ -90,27 +94,23 @@ class UDPManage{
}
try {
// print("sendData:$data");
var result = _udpSocket?.send(data, InternetAddress(host!), port!);
if(result != data.length) {
var result = _udpSocket?.send(data, InternetAddress(host), port);
if (result != data.length) {
print('❌Udp ----> send data $result ${data.length}');
_udpSocket = null;
}
}catch (e){
}
} catch (e) {}
}
bool exit() {
if(null != _udpSocket) {
if (null != _udpSocket) {
print('❌ Udp ----> close');
_udpSocket?.close();
}
return true;
}
void disposed() {
_streamSubscription?.cancel();
}
}
}