connect method
Future<void>
connect(
{ - void onDataUpdate(
- dynamic data
)?,
- void onDataConnection(
- Map data
)?,
})
Implementation
Future<void> connect({
void Function(dynamic data)? onDataUpdate,
void Function(Map data)? onDataConnection,
}) async {
while (true) {
await Future.delayed(Duration(milliseconds: 500));
if (isConnect == false) {
try {
socket = await Socket.connect(
host,
port,
sourceAddress: sourceAddress,
timeout: timeout,
);
StreamSubscription<Uint8List> listen = socket.listen(
(List<int> event) {
if (onDataUpdate != null) {
onDataUpdate(event);
} else {
return emitter.emit(event_socket_update, null, event);
}
},
onError: (a, b) {
isConnect = false;
},
onDone: () async {
isConnect = false;
if (onDataConnection != null) {
onDataConnection(
{"@type": "connection", "status": "disconnect"});
} else {
emitter.emit(event_socket_connection, null,
{"@type": "connection", "status": "disconnect"});
}
Timer.periodic(ping_interval, (timer) async {
if (onDataConnection != null) {
onDataConnection({
"@type": "connection",
"status": "reconnect",
});
} else {
emitter.emit(event_socket_connection, null,
{"@type": "connection", "status": "reconnect"});
}
try {
await connect(
onDataConnection: onDataConnection,
onDataUpdate: onDataUpdate,
);
} catch (e) {}
if (isConnect) {
timer.cancel();
}
});
},
cancelOnError: true,
);
isConnect = true;
if (onDataConnection != null) {
onDataConnection({"@type": "connection", "status": "connected"});
} else {
emitter.emit(event_socket_connection, null,
{"@type": "connection", "status": "connected"});
}
break;
} catch (e) {
if (e is SocketException) {
isConnect = false;
}
try {
await socket.done;
await socket.close();
if (onDataConnection != null) {
onDataConnection({
"@type": "connection",
"status": "reconnection",
});
} else {
emitter.emit(event_socket_connection, null, {
"@type": "connection",
"status": "reconnection",
});
}
await connect(
onDataConnection: onDataConnection,
onDataUpdate: onDataUpdate,
);
} catch (e) {
if (onDataConnection != null) {
onDataConnection({
"@type": "connection",
"status": "reconnection",
});
} else {
emitter.emit(event_socket_connection, null, {
"@type": "connection",
"status": "reconnection",
});
}
}
}
}
}
}