pychat/client.py

50 lines
1.2 KiB
Python
Raw Normal View History

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
2023-11-30 17:35:18 +01:00
HOST = 'localhost'
2023-11-30 00:22:33 +01:00
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 17:35:18 +01:00
2023-11-30 00:22:33 +01:00
def receive_message(sock):
2023-11-30 16:39:00 +01:00
while run:
2023-11-30 00:22:33 +01:00
try:
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:
break
def start_client():
2023-11-30 16:39:00 +01:00
global run
2023-11-30 00:22:33 +01:00
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
2023-11-30 17:35:18 +01:00
2023-11-30 16:39:00 +01:00
threading.Thread(target=receive_message, args=(client,), daemon=True).start()
2023-11-30 17:35:18 +01:00
try:
client.sendall(nickname.encode('utf-8'))
while run:
2023-11-30 16:39:00 +01:00
msg = input(">>")
2023-11-30 00:22:33 +01:00
if msg.lower() == "exit":
break
client.sendall(msg.encode('utf-8'))
2023-11-30 17:35:18 +01:00
except KeyboardInterrupt:
pass
finally:
run = False
print("BEENDEN")
client.sendall("exit".encode('utf-8'))
client.close()
2023-11-30 00:22:33 +01:00
if __name__ == '__main__':
start_client()