connect method
Future<void>
connect({
- required FutureOr<
void> onSocketData(- Uint8List data
- required FutureOr<
void> onSocketConnection(- SocketConnection socketConnection
- Duration delayDuration = const Duration(milliseconds: 500),
Implementation
Future<void> connect({
// void Function(dynamic data)? onDataUpdate,
// void Function(Map data)? onSocketConnection,
required FutureOr<void> Function(Uint8List data) onSocketData,
required FutureOr<void> Function(SocketConnection socketConnection)
onSocketConnection,
Duration delayDuration = const Duration(milliseconds: 500),
}) async {
while (true) {
await Future.delayed(Duration(milliseconds: 500));
if (isConnect == false) {
try {
socket = await Socket.connect(
host,
port,
sourceAddress: sourceAddress,
sourcePort: sourcePort,
timeout: timeout,
);
StreamSubscription<Uint8List> listen = socket.listen(
(Uint8List event) async {
await onSocketData(event);
},
onError: (a, b) {
isConnect = false;
},
onDone: () async {
isConnect = false;
await onSocketConnection(SocketConnection({
"@type": "socketConnection",
"status": SocketConnectionType.disconnect.name,
}));
await onSocketConnection(SocketConnection({
"@type": "socketConnection",
"status": SocketConnectionType.reconnection.name,
}));
// await connect(onSocketData: onSocketData, onSocketConnection: onSocketConnection);
Timer.periodic(ping_interval, (timer) async {
if (isConnect) {
timer.cancel();
return;
}
try {
await connect(
onSocketData: onSocketData,
onSocketConnection: onSocketConnection);
} catch (e) {}
});
},
cancelOnError: true,
);
isConnect = true;
await onSocketConnection(SocketConnection({
"@type": "socketConnection",
"status": SocketConnectionType.connected.name,
}));
break;
} catch (e) {
isConnect = false;
if (e is SocketException) {
isConnect = false;
}
try {
await socket.done;
await socket.close();
await onSocketConnection(SocketConnection({
"@type": "socketConnection",
"status": SocketConnectionType.reconnection.name,
}));
await connect(
onSocketData: onSocketData,
onSocketConnection: onSocketConnection,
delayDuration: delayDuration,
);
} catch (e) {
await onSocketConnection(SocketConnection({
"@type": "socketConnection",
"status": SocketConnectionType.reconnection.name,
}));
}
}
}
}
}