From 229965a3c96a45913da2d91860b0b0616407c99b Mon Sep 17 00:00:00 2001 From: WoNiu Date: Sat, 6 Apr 2024 17:00:54 +0800 Subject: [PATCH] =?UTF-8?q?=E7=99=BB=E5=BD=95=E8=A2=AB=E9=A1=B6=20?= =?UTF-8?q?=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/login/login_socket_utils.dart | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/lib/login/login_socket_utils.dart b/lib/login/login_socket_utils.dart index 31214aa..8fd76fb 100644 --- a/lib/login/login_socket_utils.dart +++ b/lib/login/login_socket_utils.dart @@ -43,8 +43,9 @@ class LoginSocket{ connect() async { - + socket?.close(); socket = await Socket.connect(url, port, timeout: const Duration(seconds: 30)); + heartTime = DateTime.now().millisecondsSinceEpoch; socket?.listen((event) { @@ -58,6 +59,11 @@ class LoginSocket{ // 服务器心跳 if (data['op'] == 4){ try{ + + // 更新上次心跳时间 + heartTime = DateTime.now().millisecondsSinceEpoch; + + // 心跳回报时间是否超时 int time = data['time']; time = DateTime.now().millisecondsSinceEpoch - time; if(time> (3 * 60 * 1000) ){ // 时间戳 > 3分钟 @@ -107,17 +113,17 @@ class LoginSocket{ /// 心跳 heartbeat(){ - DateTime now = DateTime.now(); - int timestamp = now.millisecondsSinceEpoch; // 秒 - heartTime = timestamp; Timer(const Duration(seconds: 20), () async { - if (socket == null){ - // 重连 - await connect(); + final time = DateTime.now().millisecondsSinceEpoch - heartTime; + if(time > (3 * 60 * 1000) ){ // 时间戳 > 3分钟 + socketError(); + return; } + heartbeat(); + Map map = { "op": 3, }; @@ -125,8 +131,6 @@ class LoginSocket{ socket?.add(dataMake(map)); socket?.flush(); - heartbeat(); - }); }