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

25
client.py Normal file → Executable file
View file

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

24
server.py Normal file → Executable file
View file

@ -1,3 +1,5 @@
#!/usr/bin/python3
import socket
import threading
@ -9,6 +11,7 @@ server.bind((HOST, PORT))
clients = []
lock = threading.Lock()
def send_to_all(conn, msg):
with lock:
for client, _ in clients:
@ -24,8 +27,8 @@ def send_to_all(conn, msg):
def handle_client(conn, addr):
nick = conn.recv(1024).decode('utf-8')
print(f"Neuer Client verbunden: {addr} (Nickname: {nick})")
send_to_all(conn, f"{nick} hat den Chat betreten")
print(f"Neuer Client verbunden: {addr} ({nick})")
send_to_all(conn, f"{nick} hat den Chat betreten.")
with lock:
clients.append((conn, nick))
@ -33,8 +36,10 @@ def handle_client(conn, addr):
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")
@ -42,33 +47,42 @@ def handle_client(conn, addr):
clients.remove((conn, nick))
conn.close()
break
print(clients)
print(f"Nachricht von {addr}: {msg}")
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")
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")
send_to_all(client, f"{nick} hat den Chat verlassen.")
client.close()
server.close()