vegbesserungen
This commit is contained in:
parent
d2af9fc1f7
commit
11396ef2cf
2 changed files with 41 additions and 54 deletions
38
client.py
38
client.py
|
@ -2,8 +2,7 @@ import socket
|
||||||
import threading
|
import threading
|
||||||
from random import randint
|
from random import randint
|
||||||
|
|
||||||
# Server-Informationen
|
HOST = 'localhost'
|
||||||
HOST = '127.0.0.1'
|
|
||||||
PORT = 12345
|
PORT = 12345
|
||||||
|
|
||||||
nickname = input("username:")
|
nickname = input("username:")
|
||||||
|
@ -13,47 +12,38 @@ if nickname == "":
|
||||||
print(f"dein username wurde zu {nickname} gesetzt.")
|
print(f"dein username wurde zu {nickname} gesetzt.")
|
||||||
|
|
||||||
run = True
|
run = True
|
||||||
|
|
||||||
def receive_message(sock):
|
def receive_message(sock):
|
||||||
""" Funktion für das Empfangen von Nachrichten """
|
|
||||||
global run
|
|
||||||
while run:
|
while run:
|
||||||
try:
|
try:
|
||||||
# Empfange die Nachricht des Servers
|
|
||||||
msg = sock.recv(1024).decode('utf-8')
|
msg = sock.recv(1024).decode('utf-8')
|
||||||
if not msg:
|
if not msg:
|
||||||
break
|
break
|
||||||
print(f"\r{msg}\n", end='', flush=True)
|
print(f"\r{msg}\n", end='', flush=True)
|
||||||
except:
|
except:
|
||||||
# Schließe die Verbindung, wenn ein Fehler auftritt
|
|
||||||
print("Verbindung getrennt.")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
def start_client():
|
def start_client():
|
||||||
""" Funktion für das Starten des Clients """
|
|
||||||
global run
|
global run
|
||||||
# Erstelle den Client-Socket und verbinde ihn mit dem Server
|
|
||||||
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
client.connect((HOST, PORT))
|
client.connect((HOST, PORT))
|
||||||
|
|
||||||
# Starte einen Thread für das Empfangen von Nachrichten
|
|
||||||
threading.Thread(target=receive_message, args=(client,), daemon=True).start()
|
threading.Thread(target=receive_message, args=(client,), daemon=True).start()
|
||||||
|
|
||||||
client.sendall(nickname.encode('utf-8'))
|
try:
|
||||||
|
client.sendall(nickname.encode('utf-8'))
|
||||||
while run:
|
while run:
|
||||||
try:
|
|
||||||
msg = input(">>")
|
msg = input(">>")
|
||||||
if msg.lower() == "exit":
|
if msg.lower() == "exit":
|
||||||
run = False
|
|
||||||
print("BEENDEN")
|
|
||||||
break
|
break
|
||||||
client.sendall(msg.encode('utf-8'))
|
client.sendall(msg.encode('utf-8'))
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
run = False
|
pass
|
||||||
print("\rBEENDEN")
|
finally:
|
||||||
break
|
run = False
|
||||||
except:
|
print("BEENDEN")
|
||||||
break
|
client.sendall("exit".encode('utf-8'))
|
||||||
|
client.close()
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
start_client()
|
start_client()
|
||||||
|
|
57
server.py
57
server.py
|
@ -1,69 +1,62 @@
|
||||||
import socket
|
import socket
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
# Server-Informationen
|
HOST = '0.0.0.0'
|
||||||
HOST = '127.0.0.1'
|
|
||||||
PORT = 12345
|
PORT = 12345
|
||||||
|
|
||||||
# Erstelle den Server-Socket
|
|
||||||
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
server.bind((HOST, PORT))
|
server.bind((HOST, PORT))
|
||||||
|
|
||||||
# Liste für die Verfolgung der Clients
|
|
||||||
clients = []
|
clients = []
|
||||||
|
lock = threading.Lock()
|
||||||
|
|
||||||
def sendanall(conn, msg):
|
def send_to_all(conn, msg):
|
||||||
for client in clients:
|
with lock:
|
||||||
if client != conn:
|
for client, _ in clients:
|
||||||
try:
|
if client != conn:
|
||||||
client.sendall(msg.encode('utf-8'))
|
try:
|
||||||
except BrokenPipeError:
|
client.sendall(msg.encode('utf-8'))
|
||||||
print("pipe error")
|
except BrokenPipeError:
|
||||||
pass
|
print("Broken Pipe Error")
|
||||||
|
pass
|
||||||
|
|
||||||
def handle_client(conn, addr):
|
def handle_client(conn, addr):
|
||||||
""" Funktion für das Behandeln eines einzelnen Clients """
|
|
||||||
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} (Nickname: {nick})")
|
||||||
sendanall(conn, f"{nick} hat den Chat betreten")
|
send_to_all(conn, f"{nick} hat den Chat betreten")
|
||||||
|
|
||||||
|
with lock:
|
||||||
|
clients.append((conn, nick))
|
||||||
|
|
||||||
# Füge den Client zur Liste hinzu
|
|
||||||
clients.append(conn)
|
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
# Empfange die Nachricht des Clients
|
|
||||||
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)
|
||||||
sendanall(conn, f"{nick} hat den Chat verlassen")
|
send_to_all(conn, f"{nick} hat den Chat verlassen")
|
||||||
clients.remove(conn)
|
with lock:
|
||||||
|
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}: {msg}")
|
||||||
|
|
||||||
# Überprüfe, ob das Socket noch geöffnet ist, bevor Sie versuchen zu senden
|
|
||||||
if conn.fileno() != -1:
|
if conn.fileno() != -1:
|
||||||
sendanall(conn, f"<{nick}>:{msg}")
|
send_to_all(conn, f"<{nick}>:{msg}")
|
||||||
except ConnectionResetError:
|
except ConnectionResetError:
|
||||||
# Wenn eine Verbindungsreset-Ausnahme auftritt (Client beendet ohne "exit" zu senden)
|
|
||||||
print("Client getrennt (Verbindungsreset):", addr)
|
print("Client getrennt (Verbindungsreset):", addr)
|
||||||
sendanall(conn, f"{nick} hat den Chat verlassen")
|
send_to_all(conn, f"{nick} hat den Chat verlassen")
|
||||||
clients.remove(conn)
|
with lock:
|
||||||
|
clients.remove((conn, nick))
|
||||||
conn.close()
|
conn.close()
|
||||||
break
|
break
|
||||||
|
|
||||||
def start_server():
|
def start_server():
|
||||||
""" Funktion für das Starten des Servers """
|
|
||||||
server.listen()
|
server.listen()
|
||||||
print(f'Server läuft auf {HOST}:{PORT}')
|
print(f'Server läuft auf {HOST}:{PORT}')
|
||||||
while True:
|
while True:
|
||||||
# Warte auf eingehende Verbindungen
|
|
||||||
conn, addr = server.accept()
|
conn, addr = server.accept()
|
||||||
# Starte einen neuen Thread für jeden Client
|
|
||||||
threading.Thread(target=handle_client, args=(conn, addr)).start()
|
threading.Thread(target=handle_client, args=(conn, addr)).start()
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@ -71,4 +64,8 @@ if __name__ == '__main__':
|
||||||
start_server()
|
start_server()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("Server wird heruntergefahren.")
|
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()
|
server.close()
|
||||||
|
|
Loading…
Reference in a new issue