2023-11-30 00:22:33 +01:00
|
|
|
import socket
|
|
|
|
import threading
|
2023-11-30 16:39:00 +01:00
|
|
|
from random import randint
|
2023-11-30 00:22:33 +01:00
|
|
|
|
|
|
|
# Server-Informationen
|
|
|
|
HOST = '127.0.0.1'
|
|
|
|
PORT = 12345
|
|
|
|
|
2023-11-30 16:39:00 +01:00
|
|
|
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.")
|
|
|
|
|
|
|
|
run = True
|
2023-11-30 00:22:33 +01:00
|
|
|
def receive_message(sock):
|
|
|
|
""" Funktion für das Empfangen von Nachrichten """
|
2023-11-30 16:39:00 +01:00
|
|
|
global run
|
|
|
|
while run:
|
2023-11-30 00:22:33 +01:00
|
|
|
try:
|
|
|
|
# Empfange die Nachricht des Servers
|
|
|
|
msg = sock.recv(1024).decode('utf-8')
|
|
|
|
if not msg:
|
|
|
|
break
|
2023-11-30 16:39:00 +01:00
|
|
|
print(f"\r{msg}\n", end='', flush=True)
|
2023-11-30 00:22:33 +01:00
|
|
|
except:
|
|
|
|
# Schließe die Verbindung, wenn ein Fehler auftritt
|
|
|
|
print("Verbindung getrennt.")
|
|
|
|
break
|
|
|
|
|
|
|
|
def start_client():
|
|
|
|
""" Funktion für das Starten des Clients """
|
2023-11-30 16:39:00 +01:00
|
|
|
global run
|
2023-11-30 00:22:33 +01:00
|
|
|
# Erstelle den Client-Socket und verbinde ihn mit dem Server
|
|
|
|
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
client.connect((HOST, PORT))
|
|
|
|
|
|
|
|
# Starte einen Thread für das Empfangen von Nachrichten
|
2023-11-30 16:39:00 +01:00
|
|
|
threading.Thread(target=receive_message, args=(client,), daemon=True).start()
|
2023-11-30 00:22:33 +01:00
|
|
|
|
|
|
|
client.sendall(nickname.encode('utf-8'))
|
2023-11-30 16:39:00 +01:00
|
|
|
|
|
|
|
while run:
|
|
|
|
try:
|
|
|
|
msg = input(">>")
|
2023-11-30 00:22:33 +01:00
|
|
|
if msg.lower() == "exit":
|
2023-11-30 16:39:00 +01:00
|
|
|
run = False
|
|
|
|
print("BEENDEN")
|
2023-11-30 00:22:33 +01:00
|
|
|
break
|
|
|
|
client.sendall(msg.encode('utf-8'))
|
2023-11-30 16:39:00 +01:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
run = False
|
|
|
|
print("\rBEENDEN")
|
|
|
|
break
|
|
|
|
except:
|
|
|
|
break
|
2023-11-30 00:22:33 +01:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
start_client()
|