From 91e7b0ace87bb602a20d245acc260177ae7fc4cc Mon Sep 17 00:00:00 2001 From: cdez Date: Mon, 21 Apr 2025 19:17:41 -0700 Subject: [PATCH] Small fix to try and address the not sending issue. --- chatserver/client.py | 10 +++++----- chatserver/server.py | 14 +++++++++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/chatserver/client.py b/chatserver/client.py index 431e3a7..6badd54 100644 --- a/chatserver/client.py +++ b/chatserver/client.py @@ -80,13 +80,13 @@ def main(): print(f"\n{server_message}") print("> ", end="", flush=True) else: - # prompt for user input - client_message = input() - if client_message.strip() == "%!": + # Prompt for user input + client_message = input("> ").strip() + if client_message == "%!": print("Exiting chat...") return - - # send message to server + + # Send message to server client_socket.send(client_message.encode('utf-8')) except Exception as e: diff --git a/chatserver/server.py b/chatserver/server.py index ccd3f97..aed86fe 100644 --- a/chatserver/server.py +++ b/chatserver/server.py @@ -29,6 +29,7 @@ def handle_client(sock, client_address, socket_list, usernames, chat_rooms, clie state = client_states.get(sock, "NORMAL") if state == "WAITING_FOR_USERNAME": + # Handle username setup usernames[sock] = message.strip() chat_rooms[sock] = "default" sock.send(b"\nUsername accepted. You are now in the 'default' chatroom.") @@ -89,14 +90,21 @@ def handle_client(sock, client_address, socket_list, usernames, chat_rooms, clie else: sock.send(b"Error: Invalid message format.") elif message.strip() == "%!": + # Handle client exit break else: - username = usernames[sock] - chat_room = chat_rooms[sock] + # Broadcast message to other clients in the same chat room + username = usernames.get(sock, "Unknown") + chat_room = chat_rooms.get(sock, "default") send_message = f"{username} >> {message}".encode('utf-8') for client_sock in socket_list: if client_sock != sock and chat_rooms.get(client_sock) == chat_room: - client_sock.send(send_message) + try: + client_sock.send(send_message) + except Exception as e: + print(f"Error sending message to {client_sock}: {e}") + client_sock.close() + socket_list.remove(client_sock) except Exception as e: print(f"Error with client {client_address}: {e}") finally: