a. Á¬½ÓµÄ¶Ô¶ËÕý³£¹Ø±Õ.
b. Á¬½ÓµÄ¶Ô¶Ë·ÇÕý³£¹Ø±Õ,Õâ°üÀ¨¶Ô¶ËÉ豸µôµç,³ÌÐò±ÀÀ£,ÍøÂç±»ÖжϵÈ.ÕâÖÖÇé¿öÊDz»ÄÜÒ²ÎÞ·¨Í¨Öª¶Ô¶ËµÄ,ËùÒÔÁ¬½Ó»áÒ»Ö±´æÔÚ,À˷ѹú¼ÒµÄ×ÊÔ´.
tcpÐÒéÕ»ÓиökeepaliveµÄÊôÐÔ,¿ÉÒÔÖ÷¶¯Ì½²âsocketÊÇ·ñ¿ÉÓÃ,²»¹ýÕâ¸öÊôÐÔµÄĬÈÏÖµºÜ´ó.
È«¾ÖÉèÖÿɸü¸Ä/etc/sysctl.conf,¼ÓÉÏ:
ÒýÓÃ:net.ipv4.tcp_keepalive_intvl = 20
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_time = 60
ÔÚ³ÌÐòÖÐÉèÖÃÈçÏÂ:
ÒýÓÃ:#include
#include
#include
#include
#include
int keepAlive = 1; // ¿ªÆôkeepaliveÊôÐÔ
int keepIdle = 60; // Èç¸ÃÁ¬½ÓÔÚ60ÃëÄÚûÓÐÈκÎÊý¾ÝÍùÀ´,Ôò½øÐÐ̽²â
int keepInterval = 5; // ̽²âʱ·¢°üµÄʱ¼ä¼ä¸ôΪ5 Ãë
int keepCount = 3; // ̽²â³¢ÊԵĴÎÊý.Èç¹ûµÚ1´Î̽²â°ü¾ÍÊÕµ½ÏìÓ¦ÁË,Ôòºó2´ÎµÄ²»ÔÙ·¢.
setsockopt(rs, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive));
setsockopt(rs, SOL_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle));
setsockopt(rs, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
setsockopt(rs, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
ÔÚ³ÌÐòÖбíÏÖΪ,µ±tcp¼ì²âµ½¶Ô¶Ësocket²»ÔÙ¿ÉÓÃʱ(²»ÄÜ·¢³ö̽²â°ü,»ò̽²â°üûÓÐÊÕµ½ACKµÄÏìÓ¦°ü),select»á·µ»Øsocket¿É¶Á,²¢ÇÒÔÚrecvʱ·µ»Ø-1,ͬʱÖÃÉÏerrnoΪETIMEDOUT.