Socket选项:SO_KEEPALIVE

   /**
     * When the keepalive option is set for a TCP socket and no data
     * has been exchanged across the socket in either direction for 
     * 2 hours (NOTE: the actual value is implementation dependent),
     * TCP automatically sends a keepalive probe to the peer. This probe is a 
     * TCP segment to which the peer must respond. 
     * One of three responses is expected:
     * 1. The peer responds with the expected ACK. The application is not 
     *    notified (since everything is OK). TCP will send another probe 
     *    following another 2 hours of inactivity.
     * 2. The peer responds with an RST, which tells the local TCP that
     *    the peer host has crashed and rebooted. The socket is closed.
     * 3. There is no response from the peer. The socket is closed. 
     *
     * The purpose of this option is to detect if the peer host crashes. 
     *
     * Valid only for TCP socket: SocketImpl
     *
     * @see Socket#setKeepAlive
     * @see Socket#getKeepAlive
     */
     public final static int SO_KEEPALIVE = 0x0008;


保持连接检测对方主机是否崩溃,避免(服务器)永远阻塞于TCP连接的输入。
设置该选项后,如果2小时内在此套接口的任一方向都没有数据交换,TCP就自动给对方发一个保持存活探测分节(keepalive probe)。这是一个对方必须响应的TCP分节.它会导致以下三种情况:

1.对方接收一切正常:以期望的ACK响应,2小时后,TCP将发出另一个探测分节。
2.对方已崩溃且已重新启动:以RST响应,套接口的待处理错误被置为ECONNRESET,套接口本身则被关闭。
3.对方无任何响应:套接口本身则被关闭。

根据上面的介绍我们可以知道对端以一种非优雅的方式断开连接的时候,我们可以设置SO_KEEPALIVE属性使得我们在2小时以后发现对方的TCP连接是否依然存在。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值