打印收到的文本时在python线程中输入值

时间:2018-01-12 15:55:45

标签: python multithreading

我正在尝试用Python开发多人迷宫游戏。 有一个处理游戏的服务器与几个客户端通信。 我遇到了客户问题,需要能够同时进行:

  • 打印他从服务器收到的消息,
  • 输入要发送到服务器的命令

我正在尝试使用Threads;但是如果服务器以原始方式发送多条消息,我的客户端将需要在打印第二条消息之前输入一些内容。

客户端是否可以在收到消息时打印消息,并仅在用户输入消息时发送消息?

这是我的代码:

import socket
from threading import Thread


connection_with_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection_with_server.connect(('localhost',12800))
print('connected to the server')

def receive_and_print():
    """ print message received from server """
    msg_recvd = connection_with_server.recv(1024)
    if (msg_recvd!=b''):
        print('The server says: \n'+msg_recvd.decode())

def enter_and_send():
    """ input a message and send it to server """
    msg_to_send = input('> ')
    if (msg_to_send != ''):
        msg_to_send = msg_to_send.encode()
        connection_with_server.send(msg_to_send)
        print('\n message sent')
    return msg_to_send

msg_to_send = b""
while msg_to_send != b"end":
    reception = Thread(target=receive_and_print)
    reception.start()
    msg_to_send=enter_and_send()
    reception.join()

print('closing connection')
connection_with_server.close()

以下是我想要的示例输出,例如,如果服务器发送两条消息,则客户端再发送一条消息,然后再发送服务器:

connected to the server
>
The server says:
message 1 from server
>
The server says:
message 2 from server
> message entered by user
message sent
>
The server says:
message 3 from server
>

我几天来一直在努力解决这个问题,任何建议都非常受欢迎! 谢谢!

编辑:看起来我设法通过在一段时间的True循环中运行receive_and_print的代码并且加入超时= 0来加入接收线程来解决问题。

0 个答案:

没有答案