我正在开发一个基于 CLI 的聊天工具,使用 WebSocket 进行实时通信。我为接收者和发送者函数实现了单独的线程,以分别处理传入消息和传出消息。但是,我在同步终端中的输出以使消息以正确的顺序显示方面遇到困难,类似于常规聊天应用程序。
def print_message(message, sender_username):
global username
print(f"{sender_username}{message}")
print(colorama.Fore.GREEN + username + colorama.Fore.RESET, end='')
def receive_messages(sock):
global finished
while not finished:
try:
raw_message = sock.recv(1024).decode()
print()
raw_message = json.loads(raw_message)
message_val = raw_message.get("Message")
sender_username, _, message = message_val.partition(':')
# Handle Join Message
if raw_message.get("Message_type") == MESSAGE_TYPE_JOIN_ROOM:
message = " is connected"
# Handle public_key receive message
if raw_message.get("Message_type") == MESSAGE_TYPE_PUBLIC_KEY:
# If store already contains the key, skip this
if store_public_key(raw_message.get("Message")):
continue
message = " public key received"
send_public_key(sock)
if raw_message.get("Message_type") == MESSAGE_TYPE_LEAVE_ROOM:
message = " is disconnected from room"
if raw_message.get("Message_type") == MESSAGE_TYPE_SIMPLE_MESSAGE:
message = decrypt_message(message)
print_simple_message(message, sender_username)
continue
print_message(message, sender_username)
except:
print("An error occurred. Exiting.")
finished = True
break
def send_messages(sock):
global finished
while not finished:
print(colorama.Fore.GREEN + username + colorama.Fore.RESET, end='')
message = input()
mes = message
encrypt_message(sock, message)
if mes == "exit()":
print("You have left the room.")
finished = True
break
#below code is to make two thread in connect_to_server function
receive_thread = threading.Thread(target=receive_messages, args=(sock,))
receive_thread.daemon = True # Set as daemon thread to terminate with the main thread
receive_thread.start()
send_thread = threading.Thread(target=send_messages, args=(sock,))
send_thread.start()
send_thread.join()
电流端子输出-
user:~/CLI_Chat_Tool$ python3 client.py private harry
Connected to the server.
@harry:
@sam is connected
@harry:
@sam public key received
@harry:
hello
@harry:
@sam: hey
hi
@harry: @harry:hi
@harry:hi
@harry:
我遇到的问题是,当发送者和接收者线程同时运行时,终端中的输出会混淆。来自接收者线程的消息可能会出现在通过发送者线程发送的用户自己的消息之前,从而导致令人困惑的用户体验。
如何正确同步和打印终端中的消息,以便它们以正确的顺序显示,就像在普通聊天应用程序中一样?
我试图用暴力来同步终端上的打印,并尝试用chatgpt和bard来解决,就像我试图删除终端的最后打印行,这是chatgpt和其他东西不可能实现的。
Java同步用于通过某种同步方法确保在给定时间点只有一个线程可以访问资源。 抖动速度测试