diff --git a/server.py b/server.py index e69de29..32e5c0b 100644 --- a/server.py +++ b/server.py @@ -0,0 +1,40 @@ +import socket +import threading + +class Connection: + sock="" + addr=0 + +HOST = "127.0.0.1" # Standard loopback interface address (localhost) +PORT = 65432 # Port to listen on (non-privileged ports are > 1023) +clients=0 +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 True: + data = conn.sock.recv(1024) + if data: + send_message(conn, data) + else: + print(f"Disconnected: {conn.addr}") + connections.remove(conn) + break + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + try: + s.bind((HOST, PORT)) + while True: + conn=Connection() + s.listen() + conn.sock, conn.addr = s.accept() + connections.append(conn) + threading.Thread(target=handle_connection, args=(conn,)).start() + except KeyboardInterrupt: + print("Shutdown server") +