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

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

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