gpt4 book ai didi

python - 错误 : Transport endpoint is not connected (Python Sockets)

转载 作者:行者123 更新时间:2023-11-28 16:26:48 25 4
gpt4 key购买 nike

我正在尝试使用 Python 中的套接字(带线程)创建一个简单的聊天应用程序。应用程序很简单,客户端必须线程一个发送数据,另一个线程接收。服务器必须有两个线程,一个用于接受客户端连接,另一个用于广播消息。但是在运行下面的代码时,我收到了错误消息

Transport endpoint is not connected

enter image description here

谁能告诉我为什么会出现这个错误

客户端

import socket, threading

def send():
msg = raw_input('Me > ')
cli_sock.send(msg)

def receive():
data = cli_sock.recv(4096)
print('> '+ str(data))

if __name__ == "__main__":
# socket
cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect
HOST = 'localhost'
PORT = 5028
cli_sock.connect((HOST, PORT))
print('Connected to remote host...')

thread_send = threading.Thread(target = send)
thread_send.start()

thread_receive = threading.Thread(target = receive)
thread_receive.start()

服务器

import socket, threading

def accept_client():
while True:
#accept
cli_sock, cli_add = ser_sock.accept()
CONNECTION_LIST.append(cli_sock)
print('Client (%s, %s) connected' % cli_add)

def broadcast_data():
while True:
data = ser_sock.recv(4096)
for csock in CONNECTION_LIST:
try:
csock.send(data)
except Exception as x:
print(x.message)
cli_sock.close()
CONNECTION_LIST.remove(cli_sock)

if __name__ == "__main__":
CONNECTION_LIST = []

# socket
ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# bind
HOST = 'localhost'
PORT = 5028
ser_sock.bind((HOST, PORT))

# listen
ser_sock.listen(1)
print('Chat server started on port : ' + str(PORT))

thread_ac = threading.Thread(target = accept_client)
thread_ac.start()

thread_bd = threading.Thread(target = broadcast_data)
thread_bd.start()

最佳答案

您没有正确使用服务器套接字。您不能在服务器套接字上recv,而是您 accept他们之间的联系; accept 返回实际的连接套接字:

ser_sock.listen(1)
sock, addr = ser_sock.accept()

print('Got connection from {}'.format(addr))

# only this *connection* socket can receive!
data = sock.recv(4096)

关于python - 错误 : Transport endpoint is not connected (Python Sockets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969714/

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