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
+39 -33
View File
@@ -1,53 +1,59 @@
import socket
import threading
# this function recieves the thread
def receive_messages(connection):
# list to keep track of all connected client sockets
clients = []
# this function handles communication with a specific client
def handle_client(connection, address):
while True:
# the try block makes it not error when it dissconnects
try:
# this waits for the message from client
# receives message from this specific client
message = connection.recv(1024).decode()
if not message:
# if the client closes the connection its empty
print("\nClient Disconnected")
break
print(f"Message from {address}: {message}")
# broadcasts this message to all OTHER clients
broadcast(message, connection)
except:
print("\nConnection closed.")
break
# the 'flush' fixes the outputs overriding each other in terminal
print(f"\nClient: {message}")
# cleans up when client disconnects
print(f"Client {address} disconnected.")
if connection in clients:
clients.remove(connection)
connection.close()
# the function for
def send_messages(connection):
while True:
# this waits for you to type
message = input()
if message.lower() == 'quit':
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)
#give socket port and address
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("localhost", 12345))
#listen for connections
server_socket.listen()
print("Server is waiting for connection...")
print("Server started. Waiting for multiple clients...")
#accept connection
conn, addr = server_socket.accept()
print("Connected to:", addr)
# the main loop to accept new connections
while True:
conn, addr = server_socket.accept()
print(f"Connected to: {addr}")
# the two threads for the inputs
receive_thread = threading.Thread(target=receive_messages, args=(conn,))
send_thread = threading.Thread(target=send_messages, args=(conn,))
clients.append(conn)
# starts the process
receive_thread.start()
send_thread.start()
# starts a new thread for every new client
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()