我已经了解了tcp中两个臭名昭着的错误之间的区别:
[Errno 54] Connection reset by peer
[Errno 32] Broken pipe
这两个错误都是tcp连接的一侧因未知原因而关闭,而另一方仍然与之通信。
write
某事,Broken pipe
被抛出时read
某事,Connection reset by peer
被抛出时我能够使用下面的Python代码重现Broken pipe
。
# tcp_server.py
def handler(client_sock, addr):
try:
print('new client from %s:%s' % addr)
finally:
client_sock.close() # close current connection directly
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 5500))
sock.listen(5)
while 1:
client_sock, addr = sock.accept()
handler(client_sock, addr)
至于客户,
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sock.connect(('', 5500))
>>> sock.send('a')
1
>>> sock.send('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.error: [Errno 32] Broken pipe
当客户端首先send
时,从服务器向客户端发送RST
数据包,从此刻起,send
将始终抛出Broken pipe
。
以上所有内容都在我的理解之内。但是,当客户端从服务器读取时,它总是返回空字符串而不是抛出Connection reset by peer
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sock.connect(('', 5500))
>>> sock.recv(1024)
''
>>> sock.recv(1024)
''
>>> sock.recv(1024)
''
>>> sock.recv(1024)
我对此感到困惑,或者一般如何重现Connection reset by peer
?
答案 0 :(得分:2)
您可以设置套接字&#34;逗留&#34;选项为0并关闭套接字以发送重置。更新服务器
import socket
import struct
import time
# tcp_server.py
def handler(client_sock, addr):
try:
print('new client from %s:%s' % addr)
time.sleep(1)
finally:
client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', 1, 0))
client_sock.close() # close current connection directly
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 5500))
sock.listen(5)
while 1:
client_sock, addr = sock.accept()
handler(client_sock, addr)
运行此客户端
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 5500))
print(sock.recv(1024))
我得到了
Traceback (most recent call last):
File "tcpclient.py", line 5, in <module>
print(sock.recv(1024))
ConnectionResetError: [Errno 104] Connection reset by peer