pychat/server.py
2023-12-02 11:24:51 +01:00

88 lines
2.2 KiB
Python
Executable file

#!/usr/bin/python3
import socket
import threading
HOST = '0.0.0.0'
PORT = 12345
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
clients = []
lock = threading.Lock()
def send_to_all(conn, msg):
with lock:
for client, _ in clients:
if client != conn:
try:
client.sendall(msg.encode('utf-8'))
except BrokenPipeError:
print("Verbindung verloren.")
with lock:
clients.remove((conn, nick))
conn.close()
break
def handle_client(conn, addr):
nick = conn.recv(1024).decode('utf-8')
print(f"Neuer Client verbunden: {addr} ({nick})")
send_to_all(conn, f"{nick} hat den Chat betreten.")
with lock:
clients.append((conn, nick))
while True:
try:
msg = conn.recv(1024).decode('utf-8')
if not msg:
break
elif msg == "exit":
print("Client getrennt:", addr)
send_to_all(conn, f"{nick} hat den Chat verlassen")
with lock:
clients.remove((conn, nick))
conn.close()
break
print(clients)
print(f"Nachricht von {addr} ({nick}): {msg}")
if conn.fileno() != -1:
send_to_all(conn, f"<{nick}>:{msg}")
except ConnectionResetError:
print("Client getrennt (Verbindungsreset):", addr)
send_to_all(conn, f"{nick} hat den Chat verlassen.")
with lock:
clients.remove((conn, nick))
conn.close()
break
def start_server():
server.listen()
print(f'Server läuft auf {HOST}:{PORT}')
while True:
conn, addr = server.accept()
threading.Thread(target=handle_client, args=(conn, addr)).start()
if __name__ == '__main__':
try:
start_server()
except KeyboardInterrupt:
print("Server wird heruntergefahren.")
with lock:
for client, nick in clients:
send_to_all(client, f"{nick} hat den Chat verlassen.")
client.close()
server.close()