diff --git a/client.py b/client.py index 7f7eeae..b9cd247 100644 --- a/client.py +++ b/client.py @@ -55,6 +55,20 @@ def term_size(): def print_white(text=""): print(wit + text + reset) +def recv_json(sock): + """Veilig JSON ontvangen, ook bij grote berichten.""" + buffer = b"" + while True: + part = sock.recv(4096) + if not part: + break + buffer += part + try: + return json.loads(buffer.decode("utf-8")) + except json.JSONDecodeError: + continue + return {} # fallback, lege dict als niks lukt + def login(): base_dir = Path(__file__).parent passwd_file = base_dir / "passwd.json" @@ -98,8 +112,7 @@ while not current_user: w, _ = term_size() print(blauw_bg + wit + "Terminal Chat ".center(w) + reset) print() - - print( groen + "========================================") + print(groen + "========================================") print(" Welcome to the Terminal Chat") print("========================================" + reset) print() @@ -123,8 +136,7 @@ except Exception as e: print("Connection failed:", e) exit() -data = s.recv(4096) -chat_data = json.loads(data.decode("utf-8")) +chat_data = recv_json(s) chat_names = list(chat_data.keys()) def draw_chat_window(messages, chatname): @@ -143,42 +155,32 @@ def draw_chat_window(messages, chatname): print("-" * w) def chat_session(chatkeuze): - global chat_messages - global chat_users - + global chat_messages, chat_users s.sendall(json.dumps({"action": "openchat", "chat_name": chatkeuze}).encode("utf-8")) - data = s.recv(4096) - chat_data = json.loads(data.decode("utf-8")) + chat_data = recv_json(s) if chatkeuze in chat_data: chat_messages = chat_data[chatkeuze].get("messages", []) chat_users = chat_data[chatkeuze].get("users", []) def receive_messages(sock): - global chat_messages - global chat_users - + global chat_messages, chat_users while True: try: - data = sock.recv(4096) - if not data: + decoded = recv_json(sock) + if not decoded: break - decoded = json.loads(data.decode("utf-8")) - - # /users response if isinstance(decoded, dict) and decoded.get("type") == "users_list": users = decoded.get("users", []) print("\nUsers:", ", ".join(users)) print(wit + "> " + reset, end="", flush=True) continue - # normale chat update if isinstance(decoded, dict) and chatkeuze in decoded: with lock: chat_messages = decoded[chatkeuze].get("messages", []) chat_users = decoded[chatkeuze].get("users", []) - draw_chat_window(chat_messages, chatkeuze) print(wit + "> " + reset, end="", flush=True) @@ -238,9 +240,8 @@ while True: if keuze.isdigit() and int(keuze) == len(chat_names)+1: nieuwe_chat = input("Name of new chat: ") s.sendall(json.dumps({"action": "new_chat", "chat_name": nieuwe_chat}).encode("utf-8")) - data = s.recv(4096) - chat_data = json.loads(data.decode("utf-8")) + chat_data = recv_json(s) chat_names = list(chat_data.keys()) elif keuze.isdigit() and 1 <= int(keuze) <= len(chat_names): chatkeuze = chat_names[int(keuze)-1] - chat_session(chatkeuze) + chat_session(chatkeuze) \ No newline at end of file