import socket import threading import select class Connection: sock="" addr=0 if 1: HOST = "0.0.0.0" # open to network else: HOST = "127.0.0.1" # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) clients=0 run = True connections=[] def send_message(conn, data): for i in connections: if i != conn: i.sock.send(data) def handle_connection(conn): with conn.sock: while run: ready_to_read, _, _ = select.select([conn.sock], [], [], 1.0) if ready_to_read: data = conn.sock.recv(1024) if data: send_message(conn, data) else: print(f"Disconnected: {conn.addr}") connections.remove(conn) break if __name__ == "__main__": hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind((HOST, PORT)) print(f"Server {hostname} on ip {IPAddr}") while run: conn=Connection() s.listen() conn.sock, conn.addr = s.accept() connections.append(conn) threading.Thread(target=handle_connection, args=(conn,)).start() except KeyboardInterrupt: run = False print("Shutdown server") finally: s.close()