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 def handle_new_connections(): hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) print(f"Server {hostname} on ip {IPAddr}") while run: conn=Connection() s.listen() ready_to_read, _, _ = select.select([s], [], [], 1.0) if ready_to_read: conn.sock, conn.addr = s.accept() connections.append(conn) threading.Thread(target=handle_connection, args=(conn,)).start() finally: s.close() if __name__ == "__main__": threading.Thread(target=handle_new_connections).start() try: print("Press Enter or CTRL + C to stop server") input() except KeyboardInterrupt: pass finally: run = False print("Shutdown server")