From b74ad5954607d34e939f9cf32876bd7ba65998f9 Mon Sep 17 00:00:00 2001
From: Guo Wenxue <guowenxue@gmail.com>
Date: Thu, 11 Apr 2024 13:08:05 +0800
Subject: [PATCH] Update socket example project

---
 project/socketd/booster/socket.c |   68 +++++++++++++++++++++++----------
 1 files changed, 47 insertions(+), 21 deletions(-)

diff --git a/project/socketd/booster/socket.c b/project/socketd/booster/socket.c
index 0206bb9..4049bfc 100644
--- a/project/socketd/booster/socket.c
+++ b/project/socketd/booster/socket.c
@@ -69,6 +69,7 @@
     {
         close(sock->fd);
         sock->fd = -1;
+        sock->connected = 0;
     }
 
     return 0;
@@ -92,6 +93,52 @@
     set_socket_rlimit(); /* set max open socket count */
 }
 #endif
+
+/*  description: check socket connect status
+ *   input args:
+ *               $sock:  socket context pointer
+ * return value: 1: connected   0:disconnected
+ */
+int socket_connected(socket_ctx_t *sock)
+{
+    struct tcp_info   info;
+    int               len=sizeof(info);
+    int               changed = 0;
+
+    if( !sock )
+    {
+        return 0;
+    }
+
+    if( sock->fd < 0 )
+    {
+        /* socket is connected before but got disconnected now */
+        changed = sock->connected ? 1 : 0;
+        sock->connected = 0;
+        goto out;
+    }
+
+    getsockopt(sock->fd, IPPROTO_TCP, TCP_INFO, &info, (socklen_t *)&len);
+    if( TCP_ESTABLISHED==info.tcpi_state )
+    {
+        /* socket is disconnected before but got connected now */
+        changed = !sock->connected ? 1 : 0;
+        sock->connected = 1;
+    }
+    else
+    {
+        /* socket is connected before but got disconnected now */
+        changed = sock->connected ? 1 : 0;
+        sock->connected = 0;
+    }
+
+out:
+    if( changed )
+    {
+        log_info("socket status got %s\n", sock->connected?"connected":"disconnected");
+    }
+    return sock->connected;
+}
 
 /*  description: socket connect to server in block mode
  *   input args:
@@ -288,30 +335,9 @@
 }
 
 
-
 /*+-------------------------------------------------------------------+
  *|                socket utils function                              |
  *+-------------------------------------------------------------------+*/
-
-
-/*  socket connected or not: <0: failure  0:ok */
-int sock_check_connect(int sockfd)
-{
-    struct tcp_info   info;
-    int               len=sizeof(info);
-
-    if( sockfd < 0 )
-        return -1;
-
-    getsockopt(sockfd, IPPROTO_TCP, TCP_INFO, &info, (socklen_t *)&len);
-
-    if( TCP_CLOSE==info.tcpi_state || TCP_CLOSING==info.tcpi_state || TCP_CLOSE_WAIT==info.tcpi_state )
-    {
-        return -3;
-    }
-
-    return -0;
-}
 
 /* description: set socket listen port as reusable, fix port already used bug  */
 int socket_set_reuseaddr(int sockfd)

--
Gitblit v1.9.1