Small fix to try and address the not sending issue.

This commit is contained in:
Charles Descamps 2025-04-21 19:17:41 -07:00
parent d157cf8189
commit 91e7b0ace8
2 changed files with 16 additions and 8 deletions

View file

@ -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: