关于tcp socket出现的”connection reset by peer“和“broken pipe”

在socket通信过程中,经常发现客户端或者服务器的日志中出现“broken pipe”或者“connection reset by peer”的错误提示。之前一直以为自己理解了这两个错误异常提示所包含的意义,而实际理解完全错误。我的错误理解和下面这段来自blogspot的表述差不多.

Maybe I'm just dumb, but I always thought "broken pipe" meant, "the other end of this socket closed before I finished sending something" and "connection reset by peer" meant, well, roughly the same thing. (As well as indicating some slightly more esoteric problems.) 
Turns out though, "broken pipe" actually means "I just tried to send something and the socket was already closed to sending." 
So in the following example, if the other end of (TCP) socket "sock" closes or dies before the write method, "connection reset by peer" will be raised. The next write will give a broken-pipe error, since the socket now knows that further sending is invalid. 
try:
    sock.write('foo')
except:
    pass # connection reset by peer
sock.write('bar') # broken pipe

“connection reset by peer”和”broken pipe”出现的场景:
1)往一个对端已经close的通道写数据的时候,对方的tcp会收到这个报文,并且反馈一个reset报文。当收到reset报文的时候,继续做select读数据的时候就会抛出Connect reset by peer的异常,。

2)当第一次往一个对端已经close的通道写数据的时候会和上面的情况一样,会收到reset报文。当再次往这个socket写数据的时候,就会抛出Broken pipe了 。根据tcp的约定,当收到reset包的时候,上层必须要做出处理,调用将socket文件描述符进行关闭,其实也意味着pipe会关闭,因此会抛出这个顾名思义的异常。

下面的两篇文章对这种问题解释的很清楚:
1)从tcp原理角度理解Broken pipe和Connection reset by peer的区别.
2)遭遇SIGPIPE.

此条目发表在os/linux分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>