美文网首页网络
【tcp】关于tcp socket出现的“connection

【tcp】关于tcp socket出现的“connection

作者: Bogon | 来源:发表于2022-05-31 00:43 被阅读0次

    在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

    ```

    reset报文发送场景

    RST的标志位,这个标识为在如下几种情况下会被设置,以下是我了解的情况,可能还有更多的场景,没有验证:

    1. 当尝试和未开放的服务器端口建立tcp连接时,服务器tcp将会直接向客户端发送reset报文

    2. 双方之前已经正常建立了通信通道,也可能进行过了交互,当某一方在交互的过程中发生了异常,如崩溃等,异常的一方会向对端发送reset报文,通知对方将连接关闭

    3. 当收到TCP报文,但是发现该报文不是已建立的TCP连接列表可处理的,则其直接向对端发送reset报文

    4. ack报文丢失,并且超出一定的重传次数或时间后,会主动向对端发送reset报文释放该TCP连接

    其实我们java异常里看到的Broken pipe或者Connection reset by peer信息不是jdk或者jvm里定义的,我看到这些关键字往往会首先搜索下jdk或者hotspot源码找到位置进行上下文分析,但是没找到,后面才想到应该是Linux或者glibc里定义的,果然在glibc里看到了如上的描述和定义。

    对于Broken pipe在管道的另外一端没有进程在读的时候就会抛出此异常,Connection reset by peer的描述其实不是很正确,从我的实践来看只描述了一方面,其实在某一端正常close之后,也是可能会有此异常的。

    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会关闭,因此会抛出这个顾名思义的异常。

    参考

    从tcp原理角度理解Broken pipe和Connection Reset by Peer的区别

    http://lovestblog.cn/blog/2014/05/20/tcp-broken-pipe

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

    http://mdba.cn/2015/04/07/%E5%85%B3%E4%BA%8Etcp-socket%E5%87%BA%E7%8E%B0%E7%9A%84connection-reset-by-peer%E5%92%8Cbroken-pipe

    相关文章

      网友评论

        本文标题:【tcp】关于tcp socket出现的“connection

        本文链接:https://www.haomeiwen.com/subject/foagprtx.html