我是靠谱客的博主 孝顺鸡,最近开发中收集的这篇文章主要介绍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连接是否依然存在。

最后

以上就是孝顺鸡为你收集整理的Socket选项:SO_KEEPALIVE的全部内容,希望文章能够帮你解决Socket选项:SO_KEEPALIVE所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部