我想了解为什么我必须等待接收器线程结束其工作才能执行其他任何操作。 我知道我的sock_listen函数正在等待连接,这就是它的含义,但是我不明白为什么这不是在线程“内”发生的。
很抱歉,如果这是一个愚蠢的问题,但我有点迷茫! 预先谢谢你!
def sock_listen(address, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (address,port)
print("Starting listener on %s and port %s" % server_address)
sock.bind(server_address)
sock.listen(1)
while True:
print("[-] Waiting for connection")
connection, client_address = sock.accept()
print("[+] Connection from " + str(client_address))
data = connection.recv(256)
while (data) :
print("[" + time.strftime("%H:%M:%S") + "] " + str(data))
data = connection.recv(256)
receiver = threading.Thread(sock_listen("localhost",10000))
print("Nothing reaches me, I can not be printed until the sock_connect func is done looping!")
receiver.start()
我的目标是进行TCP简单聊天,在该聊天中,专用线程将处理并打印传入消息,而主进程将发送用户输入(消息)
答案 0 :(得分:0)
编写threading.Thread(sock_listen("localhost",10000))
时,您已经在调用sock_listen
并将此调用的结果传递到Thread
构造函数中。
您需要将可调用的sock_listen
作为target
传递,并将sock_listen
的参数分别传递给Thread
:
receiver = threading.Thread(target=sock_listen, args=("localhost",10000))
启动后,您的目标函数将在新线程中被调用。