60 lines
1.7 KiB
Python
60 lines
1.7 KiB
Python
import socket
|
|
import threading
|
|
|
|
# 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:
|
|
try:
|
|
# receives message from this specific client
|
|
message = connection.recv(1024).decode()
|
|
if not message:
|
|
break
|
|
|
|
print(f"Message from {address}: {message}")
|
|
|
|
# broadcasts this message to all OTHER clients
|
|
broadcast(message, connection)
|
|
except:
|
|
break
|
|
|
|
# cleans up when client disconnects
|
|
print(f"Client {address} disconnected.")
|
|
if connection in clients:
|
|
clients.remove(connection)
|
|
connection.close()
|
|
|
|
|
|
# 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)
|
|
|
|
|
|
# creates and sets up socket
|
|
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
server_socket.bind(("localhost", 12345))
|
|
server_socket.listen()
|
|
print("Server started. Waiting for multiple clients...")
|
|
|
|
# the main loop to accept new connections
|
|
while True:
|
|
conn, addr = server_socket.accept()
|
|
print(f"Connected to: {addr}")
|
|
|
|
clients.append(conn)
|
|
|
|
# starts a new thread for every new client
|
|
thread = threading.Thread(target=handle_client, args=(conn, addr))
|
|
thread.start()
|