如果两个设备(智能手机和PC)都在线,则我的Flutter应用程序连接到c#服务器套接字。
如果服务器套接字处于脱机状态,则Flutter应用会尝试每两秒钟进行连接。
几分钟后重新连接时,将接受连接,但开始时未接收到数据,但几秒钟后一次接收到许多消息。
我试图在2秒超时后销毁客户端套接字(Flutter),但这无济于事。
重新启动应用程序时,一切正常。我丢失了应用程序重启功能是什么?
Future<void> ConnectToPC() async {
//Called periodically from Timer
String Sucess = 'Already trying to connect';
if (!tryingToConnect) {
try {
print('Trying to connect to $cardIP on port $cardPort');
tryingToConnect = true;
ClientSocket = await Socket.connect(cardIP, int.parse(cardPort))
.timeout(Duration(seconds: 2));
print('Socket connected!');
ClientSocket.listen(HandleIcomingEvents,
onError: SocketErr, onDone: SocketClose, cancelOnError: false);
connected = true;
tryingToConnect = false;
Sucess = 'Connected';
cardstate = 'Online';
//initiate communication, use response for initial stuff
SendToServer("!GETREADY!\n");
//Await pong within the specified timeout
PongReceived = DateTime.now();
//Start send and check !PING! periodically
SetPingTimer('ON');
} on TimeoutException catch (e) {
print('Timeout');
tryingToConnect = false;
Sucess = 'Connection failed';
if (ClientSocket!=null) ClientSocket.destroy();
} on OSError {
print('OS error');
} on Exception catch (e) {
print('Socket connection error $e');
tryingToConnect = false;
Sucess = 'Connection failed';
WhenDisconnected();
}
}
setState(() {
StatusText = Sucess;
});
}
void WhenDisconnected() {
SetPingTimer('OFF');
connected = false;
cardstate = 'Not connected';
ClientSocket.destroy();
gotTheJo=false;
ClientSocket=null;
}
通过ping发送一次,我还会收到多个“ pong” 等待ClientSocket.add(utf8.encode(TextInhalt));