gpt4 book ai didi

python3操作系统错误: [Errno 107] Transport endpoint is not connected

转载 作者:太空宇宙 更新时间:2023-11-03 16:48:19 28 4
gpt4 key购买 nike

我尝试在 Python3 上进行聊天。这是我的代码:

import socket
import threading

print("Server starts working")

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 57054))
sock.listen(2)

conn, addr = sock.accept()


def get_message():
while True:
data = sock.recv(1024).decode()
if len(data) != 0:
print("Some guy: ", data)


def send_message():
while True:
message = input()
if len(message) != 0:
message = str.encode(message)
sock.send(message)
print("You: ", message)


def run():
get_message_thread = threading.Thread(target=get_message())
send_message_thread = threading.Thread(target=send_message())

get_message_thread.daemon = True
send_message_thread.daemon = True

get_message_thread.start()
send_message_thread.start()


run()

sock.close()

但是在执行并从其他客户端发送消息后,我收到一条错误消息:

Server starts working
Traceback (most recent call last):
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 40, in <module>
run()
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 30, in run
get_message_thread = threading.Thread(target=get_message())
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 15, in get_message
data = sock.recv(1024).decode()
OSError: [Errno 107] Transport endpoint is not connected

Process finished with exit code 1

我读到,sock.accept() 存在一些问题,但正如我所想,这里一切都很好。

最佳答案

你的程序有很多缺陷。正如 zondo 提到的,你错误地超越了目标。它们应该类似于 threading.Thread(target=get_message)。第二个问题是,您应该使用 conn (而不是 sock)来发送和接收数据。第三个问题是,主线程在接受调用时阻塞,并将等待连接。但一旦它接受连接,它就会退出。在主线程中,您应该等待 get_message_thread 和 send_message_thread。尝试修改后的代码:

import socket
import threading

print("Server starts working")

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 57054))
sock.listen(2)

conn, addr = sock.accept()


def get_message():
while True:
data = conn.recv(1024).decode()
if len(data) != 0:
print("Some guy: ", data)


def send_message():
while True:
message = input()
if len(message) != 0:
message = str.encode(message)
conn.send(message)
print("You: ", message)


def run():
get_message_thread = threading.Thread(target=get_message)
send_message_thread = threading.Thread(target=send_message)

get_message_thread.daemon = True
send_message_thread.daemon = True

get_message_thread.start()
send_message_thread.start()
get_message_thread.join()
send_message_thread.join()

run()

sock.close()

关于python3操作系统错误: [Errno 107] Transport endpoint is not connected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113938/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com