Eddited files to comply with part3

This commit is contained in:
2026-04-19 15:27:30 -04:00
parent 03931fddfe
commit a10c3e7abd
3 changed files with 54 additions and 56 deletions
+13 -20
View File
@@ -2,41 +2,34 @@ import socket
import threading import threading
# function for messages from server # this function is for receiving messages from the server (broadcasted from the other clients)
def receive_server(s): def receive_messages(s):
while True: while True:
# the try block makes it not error when it dissconnects
try: try:
message = s.recv(1024).decode() message = s.recv(1024).decode()
if not message: if not message:
print("\nServer closed the connection")
break
print(f"\nServer: {message}")
except:
print("\nDisconnected from server.") print("\nDisconnected from server.")
break break
# overwrites the current line to keep the UI clean
print(f"\rIncoming: {message}")
print("You: ", end="", flush=True)
except:
print("\nConnection lost.")
break
#create socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#connect to server
client_socket.connect(("localhost", 12345)) client_socket.connect(("localhost", 12345))
print("Connected to server.") print("Connected to Group Chat.")
print("Type 'quit' to exit.")
# thread to listen for messages while we are typing
# starts the recieving thread receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))
receive_thread = threading.Thread(target=receive_server, args=(client_socket,))
receive_thread.start() receive_thread.start()
# loop for sending the messages
while True: while True:
msg = input() msg = input("You: ")
if msg.lower() == 'quit': if msg.lower() == "quit":
break break
client_socket.send(msg.encode()) client_socket.send(msg.encode())
#close connection
client_socket.close() client_socket.close()
+2 -3
View File
@@ -1,7 +1,6 @@
How to run code: How to run code:
First run server.py in the terminal First run server.py in the terminal
Next run client.py on a seperate terminal Next run client.py on a seperate terminal for every user you want
Now that you have established a connection you can send messages to eachother until you want to stop Now that you have established a connection you can send messages between the clients until you want to stop
To end the connection type 'quit' on either side to end the connction
+37 -31
View File
@@ -1,53 +1,59 @@
import socket import socket
import threading import threading
# this function recieves the thread # list to keep track of all connected client sockets
def receive_messages(connection): clients = []
# this function handles communication with a specific client
def handle_client(connection, address):
while True: while True:
# the try block makes it not error when it dissconnects
try: try:
# this waits for the message from client # receives message from this specific client
message = connection.recv(1024).decode() message = connection.recv(1024).decode()
if not message: if not message:
# if the client closes the connection its empty
print("\nClient Disconnected")
break break
print(f"Message from {address}: {message}")
# broadcasts this message to all OTHER clients
broadcast(message, connection)
except: except:
print("\nConnection closed.")
break break
# the 'flush' fixes the outputs overriding each other in terminal # cleans up when client disconnects
print(f"\nClient: {message}") print(f"Client {address} disconnected.")
if connection in clients:
clients.remove(connection)
# the function for
def send_messages(connection):
while True:
# this waits for you to type
message = input()
if message.lower() == 'quit':
connection.close() connection.close()
break
connection.send(message.encode())
# the function to send a message to everyone except the sender
def broadcast(message, sender_connection):
for client in clients:
if client != sender_connection:
try:
client.send(message.encode())
except:
client.close()
if client in clients:
clients.remove(client)
#create socket
# creates and sets up socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#give socket port and address server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("localhost", 12345)) server_socket.bind(("localhost", 12345))
#listen for connections
server_socket.listen() server_socket.listen()
print("Server is waiting for connection...") print("Server started. Waiting for multiple clients...")
#accept connection # the main loop to accept new connections
while True:
conn, addr = server_socket.accept() conn, addr = server_socket.accept()
print("Connected to:", addr) print(f"Connected to: {addr}")
# the two threads for the inputs clients.append(conn)
receive_thread = threading.Thread(target=receive_messages, args=(conn,))
send_thread = threading.Thread(target=send_messages, args=(conn,))
# starts the process # starts a new thread for every new client
receive_thread.start() thread = threading.Thread(target=handle_client, args=(conn, addr))
send_thread.start() thread.start()