From b628ce0ce2420cdafe72085ecee01bbd69792269 Mon Sep 17 00:00:00 2001
From: Paul-Winpenny <92634321+Paul-Winpenny@users.noreply.github.com>
Date: Mon, 4 Nov 2024 16:56:19 +0000
Subject: [PATCH] Added graceful disconnect on the pi's side

---
 Connectivity/SampleServerPi.py | 71 +++++++++++++++++++---------------
 1 file changed, 40 insertions(+), 31 deletions(-)

diff --git a/Connectivity/SampleServerPi.py b/Connectivity/SampleServerPi.py
index 30465635..17591102 100644
--- a/Connectivity/SampleServerPi.py
+++ b/Connectivity/SampleServerPi.py
@@ -13,46 +13,55 @@ def broadcast_presence():
     while True:
         message = b"ROBOBIN_PRESENT"
         sock.sendto(message, (UDP_IP, UDP_PORT))
+        print("Broadcasting: {}".format(message.decode()))
         time.sleep(5)
 
 def handle_client_connection(client_socket):
-    while True:
-        request = client_socket.recv(1024)
-        if not request:
-            break 
-        message = request.decode()
-        print("Received from client: {}".format(message))
-
-        if message == "PING":
-            print("Received PING from client.")  
-            response = b"PONG"  
-            client_socket.sendall(response)
-
-    client_socket.close()
-    print("Client disconnected.")
-
+    try:
+        while True:
+            request = client_socket.recv(1024)
+            if not request:
+                print("No request received, closing connection.")
+                break  # Connection closed by the client
+            message = request.decode()
+            print("Received from client: {}".format(message))
+
+            if message == "PING":
+                print("Received PING from client.")  
+                response = b"PONG"  
+                client_socket.sendall(response)
+
+    except ConnectionResetError:
+        print("Client connection was forcibly closed.")
+    except Exception as e:
+        print(f"An error occurred while handling the client connection: {e}")
+    finally:
+        client_socket.close()
+        print("Client disconnected.")
 
 def listen_for_connections():
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     sock.bind(('', LISTEN_PORT))
 
     while True:
-        data, addr = sock.recvfrom(1024)
-        if data.decode() == "CONNECT":
-            print("Received connection request from {}".format(addr))
-
-            # Create a TCP socket to accept connections
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp_socket:
-                tcp_socket.bind(('', 5006))  # Listen on the fixed TCP port
-                tcp_socket.listen(1)
-                print("Listening for TCP connection...")
-
-                client_socket, client_addr = tcp_socket.accept()
-                print("Client connected from {}".format(client_addr))
-
-                # Spawn a new thread for handling the client connection
-                threading.Thread(target=handle_client_connection, args=(client_socket,)).start()
-
+        try:
+            data, addr = sock.recvfrom(1024)
+            if data.decode() == "CONNECT":
+                print("Received connection request from {}".format(addr))
+
+                # Create a TCP socket to accept connections
+                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp_socket:
+                    tcp_socket.bind(('', 5006))  # Listen on the fixed TCP port
+                    tcp_socket.listen(1)
+                    print("Listening for TCP connection...")
+
+                    client_socket, client_addr = tcp_socket.accept()
+                    print("Client connected from {}".format(client_addr))
+
+                    # Spawn a new thread for handling the client connection
+                    threading.Thread(target=handle_client_connection, args=(client_socket,)).start()
+        except Exception as e:
+            print(f"An error occurred while listening for connections: {e}")
 
 # Start the broadcasting and listening in separate threads
 broadcast_thread = threading.Thread(target=broadcast_presence)
-- 
GitLab