Skip to content
Snippets Groups Projects
Commit b628ce0c authored by Paul-Winpenny's avatar Paul-Winpenny
Browse files

Added graceful disconnect on the pi's side

parent 010f732d
Branches
No related tags found
No related merge requests found
......@@ -13,13 +13,16 @@ 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):
try:
while True:
request = client_socket.recv(1024)
if not request:
break
print("No request received, closing connection.")
break # Connection closed by the client
message = request.decode()
print("Received from client: {}".format(message))
......@@ -28,15 +31,20 @@ def handle_client_connection(client_socket):
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:
try:
data, addr = sock.recvfrom(1024)
if data.decode() == "CONNECT":
print("Received connection request from {}".format(addr))
......@@ -52,7 +60,8 @@ def listen_for_connections():
# 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)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment