Paar Verschönerungen

This commit is contained in:
The Wobbler 2023-12-02 11:24:51 +01:00
parent a3197dbc28
commit 59e85a07fa
2 changed files with 37 additions and 12 deletions

21
client.py Normal file → Executable file
View file

@ -1,18 +1,22 @@
#!/usr/bin/python3
import socket import socket
import threading import threading
from random import randint from random import randint, choice
HOST = 'localhost' HOST = 'localhost'
PORT = 12345 PORT = 12345
nickname = input("username:") nickname = input("Username: ")
if nickname == "": if nickname == "":
nickname = ["tux","gnu","wilber","xue","puffy"][randint(0,4)] nickname = choice(["Tux", "Gnu", "Wilber", "Xue", "Puffy"])
nickname += str(randint(1000, 9999)) nickname += str(randint(1000, 9999))
print(f"dein username wurde zu {nickname} gesetzt.") print(f"Dein username wurde auf {nickname} gesetzt.")
run = True run = True
def receive_message(sock): def receive_message(sock):
print_lock = threading.Lock() print_lock = threading.Lock()
while run: while run:
@ -20,11 +24,14 @@ def receive_message(sock):
msg = sock.recv(1024).decode('utf-8') msg = sock.recv(1024).decode('utf-8')
if not msg: if not msg:
break break
with print_lock: with print_lock:
print(f"\r{msg}\n", end='', flush=True) print(f"\r{msg}\n", end='', flush=True)
except: except:
break break
def start_client(): def start_client():
global run global run
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@ -38,14 +45,18 @@ def start_client():
msg = input(">> ") msg = input(">> ")
if msg.lower() == "exit": if msg.lower() == "exit":
break break
client.sendall(msg.encode('utf-8')) client.sendall(msg.encode('utf-8'))
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
finally: finally:
run = False run = False
print("BEENDEN") print("\nBEENDEN")
client.sendall("exit".encode('utf-8')) client.sendall("exit".encode('utf-8'))
client.close() client.close()
if __name__ == '__main__': if __name__ == '__main__':
start_client() start_client()

24
server.py Normal file → Executable file
View file

@ -1,3 +1,5 @@
#!/usr/bin/python3
import socket import socket
import threading import threading
@ -9,6 +11,7 @@ server.bind((HOST, PORT))
clients = [] clients = []
lock = threading.Lock() lock = threading.Lock()
def send_to_all(conn, msg): def send_to_all(conn, msg):
with lock: with lock:
for client, _ in clients: for client, _ in clients:
@ -24,8 +27,8 @@ def send_to_all(conn, msg):
def handle_client(conn, addr): def handle_client(conn, addr):
nick = conn.recv(1024).decode('utf-8') nick = conn.recv(1024).decode('utf-8')
print(f"Neuer Client verbunden: {addr} (Nickname: {nick})") print(f"Neuer Client verbunden: {addr} ({nick})")
send_to_all(conn, f"{nick} hat den Chat betreten") send_to_all(conn, f"{nick} hat den Chat betreten.")
with lock: with lock:
clients.append((conn, nick)) clients.append((conn, nick))
@ -33,8 +36,10 @@ def handle_client(conn, addr):
while True: while True:
try: try:
msg = conn.recv(1024).decode('utf-8') msg = conn.recv(1024).decode('utf-8')
if not msg: if not msg:
break break
elif msg == "exit": elif msg == "exit":
print("Client getrennt:", addr) print("Client getrennt:", addr)
send_to_all(conn, f"{nick} hat den Chat verlassen") send_to_all(conn, f"{nick} hat den Chat verlassen")
@ -42,33 +47,42 @@ def handle_client(conn, addr):
clients.remove((conn, nick)) clients.remove((conn, nick))
conn.close() conn.close()
break break
print(clients) print(clients)
print(f"Nachricht von {addr}: {msg}") print(f"Nachricht von {addr} ({nick}): {msg}")
if conn.fileno() != -1: if conn.fileno() != -1:
send_to_all(conn, f"<{nick}>:{msg}") send_to_all(conn, f"<{nick}>:{msg}")
except ConnectionResetError: except ConnectionResetError:
print("Client getrennt (Verbindungsreset):", addr) print("Client getrennt (Verbindungsreset):", addr)
send_to_all(conn, f"{nick} hat den Chat verlassen") send_to_all(conn, f"{nick} hat den Chat verlassen.")
with lock: with lock:
clients.remove((conn, nick)) clients.remove((conn, nick))
conn.close() conn.close()
break break
def start_server(): def start_server():
server.listen() server.listen()
print(f'Server läuft auf {HOST}:{PORT}') print(f'Server läuft auf {HOST}:{PORT}')
while True: while True:
conn, addr = server.accept() conn, addr = server.accept()
threading.Thread(target=handle_client, args=(conn, addr)).start() threading.Thread(target=handle_client, args=(conn, addr)).start()
if __name__ == '__main__': if __name__ == '__main__':
try: try:
start_server() start_server()
except KeyboardInterrupt: except KeyboardInterrupt:
print("Server wird heruntergefahren.") print("Server wird heruntergefahren.")
with lock: with lock:
for client, nick in clients: for client, nick in clients:
send_to_all(client, f"{nick} hat den Chat verlassen") send_to_all(client, f"{nick} hat den Chat verlassen.")
client.close() client.close()
server.close() server.close()