相关疑难解决方法(0)

在第二次发送之前,Python不会检测到已关闭的套接字

当我在连接的一端关闭套接字时,另一端在第二次发送数据时会收到错误,但不是第一次:

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 12345))
server.listen(1)

client = socket.create_connection(("localhost",12345))
sock, addr = server.accept()
sock.close()

client.sendall("Hello World!")    # no error
client.sendall("Goodbye World!")  # error happens here
Run Code Online (Sandbox Code Playgroud)

我已经尝试设置TCP_NODELAY,使用send而不是sendall检查fileno(),我找不到任何方法来获取第一个发送错误,甚至检测到它失败后. 编辑:sock.shutdown之前打电话sock.close没有帮助. 编辑#2:即使time.sleep在结束之后和写作之前添加也没关系. 编辑#3:检查返回的字节数send没有帮助,因为它总是返回消息中的字节数.

因此,如果我想检测错误,我能想出的唯一解决方案就是sendall使用一个client.sendall("")会引发错误的解决方案.但这似乎很苛刻.我在Linux 2.6.x上,所以即使解决方案仅适用于该操作系统,我也会感到高兴.

python sockets

16
推荐指数
1
解决办法
6866
查看次数

标签 统计

python ×1

sockets ×1