Create the client, and modify the server.

This commit is contained in:
Charles Descamps 2025-03-13 16:05:26 -07:00
parent 5443d01d5c
commit 12eb4fb3f5
2 changed files with 53 additions and 6 deletions

View file

@ -0,0 +1,47 @@
import socket
import sys
import select
SERVER_HOST = 'localhost'
SERVER_PORT = 8181
BUFFER_SIZE = 1024
def main():
# create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to the server
client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f"Connected to chat server at {SERVER_HOST}:{SERVER_PORT}")
while True:
# use select to wait for either server messages or user input
read_sockets, _, _ = select.select([client_socket, sys.stdin], [], [])
for sock in read_sockets:
if sock == client_socket:
# receive message from server
server_message = client_socket.recv(BUFFER_SIZE).decode('utf-8')
if not server_message:
print("Disconnected from server")
return
print(f"\n{server_message}")
print("> ", end="", flush=True)
else:
# prompt for user input
client_message = input()
if client_message.strip() == "%!":
print("Exiting chat...")
return
# send message to server
client_socket.send(client_message.encode('utf-8'))
except Exception as e:
print(f"Error: {e}")
finally:
client_socket.close()
print("Connection closed")
if __name__ == "__main__":
main()

View file

@ -48,7 +48,7 @@ def main():
print("\nAccepted connection from new client.") print("\nAccepted connection from new client.")
client_socket.send(b"\nWelcome to the chat server!\n") client_socket.send(b"\nWelcome to the chat server!\n")
client_socket.send(b"\nUse '%!' to exit, or '%?' for help.\n") client_socket.send(b"\nUse '%!' to exit, or '%?' for help.\n")
client_socket.send(b"\nType in a username: \n") client_socket.send(b"\nType in a username: ")
client_states[client_socket] = "WAITING_FOR_USERNAME" client_states[client_socket] = "WAITING_FOR_USERNAME"
# otherwise the socket is a client socket. # otherwise the socket is a client socket.
else: else:
@ -60,17 +60,17 @@ def main():
if state == "WAITING_FOR_USERNAME": if state == "WAITING_FOR_USERNAME":
usernames[sock] = message.strip() usernames[sock] = message.strip()
chat_rooms[sock] = "default" chat_rooms[sock] = "default"
sock.send(b"\nUsername accepted. You are now in the 'default' chatroom.\n") sock.send(b"\nUsername accepted. You are now in the 'default' chatroom.")
client_states[sock] = "NORMAL" client_states[sock] = "NORMAL"
elif state == "WAITING_FOR_NEW_USERNAME": elif state == "WAITING_FOR_NEW_USERNAME":
usernames[sock] = message.strip() usernames[sock] = message.strip()
sock.send(b"\nUsername changed successfully.\n") sock.send(b"\nUsername changed successfully.")
print(f"\nClient switched username to {usernames[sock]}.") print(f"\nClient switched username to {usernames[sock]}.")
client_states[sock] = "NORMAL" client_states[sock] = "NORMAL"
elif state == "WAITING_FOR_NEW_CHATROOM": elif state == "WAITING_FOR_NEW_CHATROOM":
old_chatroom = chat_rooms[sock] old_chatroom = chat_rooms[sock]
chat_rooms[sock] = message.strip() chat_rooms[sock] = message.strip()
sock.send(f"\nSwitched to chatroom '{chat_rooms[sock]}.'\n".encode('utf-8')) sock.send(f"\nSwitched to chatroom '{chat_rooms[sock]}.'".encode('utf-8'))
print(f"\nClient switched to chatroom '{chat_rooms[sock]}.'") print(f"\nClient switched to chatroom '{chat_rooms[sock]}.'")
if old_chatroom != "default" and old_chatroom not in chat_rooms.values(): if old_chatroom != "default" and old_chatroom not in chat_rooms.values():
print(f"\nChatroom '{old_chatroom}' is empty and removed.") print(f"\nChatroom '{old_chatroom}' is empty and removed.")
@ -93,10 +93,10 @@ def main():
sock.send(b"\t%* : Switch to another chatroom.\n") sock.send(b"\t%* : Switch to another chatroom.\n")
sock.send(b"\t%$ : Change Username.\n") sock.send(b"\t%$ : Change Username.\n")
elif message.strip() == "%*": elif message.strip() == "%*":
sock.send(b"\nEnter chatroom name: \n") sock.send(b"\nEnter chatroom name: ")
client_states[sock] = "WAITING_FOR_NEW_CHATROOM" client_states[sock] = "WAITING_FOR_NEW_CHATROOM"
elif message.strip() == "%$": elif message.strip() == "%$":
sock.send(b"\nEnter new username: \n") sock.send(b"\nEnter new username: ")
client_states[sock] = "WAITING_FOR_NEW_USERNAME" client_states[sock] = "WAITING_FOR_NEW_USERNAME"
else: else:
username = usernames[sock] username = usernames[sock]