51 lines
1.2 KiB
Python
51 lines
1.2 KiB
Python
import socket
|
|
import threading
|
|
from random import randint
|
|
|
|
HOST = 'localhost'
|
|
PORT = 12345
|
|
|
|
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
|
|
|
|
def receive_message(sock):
|
|
print_lock = threading.Lock()
|
|
while run:
|
|
try:
|
|
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)
|
|
client.connect((HOST, PORT))
|
|
|
|
threading.Thread(target=receive_message, args=(client,), daemon=True).start()
|
|
|
|
try:
|
|
client.sendall(nickname.encode('utf-8'))
|
|
while run:
|
|
msg = input(">>")
|
|
if msg.lower() == "exit":
|
|
break
|
|
client.sendall(msg.encode('utf-8'))
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
run = False
|
|
print("BEENDEN")
|
|
client.sendall("exit".encode('utf-8'))
|
|
client.close()
|
|
|
|
if __name__ == '__main__':
|
|
start_client()
|