static void set_keepalive(int fd) { int keepAlive = config_get_intval("SO_KEEPALIVE",1); if (keepAlive == 0) { return; } setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE,(void*)&keepAlive,sizeof(keepAlive)); // 这里default给了65秒,自定义的话到配置文件中修改,一般心跳60秒即可,客户端有延时 int keepIdle = config_get_intval("TCP_KEEPIDLE",65); setsockopt(fd,SOL_TCP,TCP_KEEPIDLE,(void *)&keepIdle,sizeof(keepIdle)); int keepInterval = config_get_intval("TCP_KEEPINTVL",10); setsockopt(fd,TCP_KEEPINTVL,(void *)&keepInterval,sizeof(keepInterval)); int keepCount = config_get_intval("TCP_KEEPCNT",TCP_KEEPCNT,(void *)&keepCount,sizeof(keepCount)); }
也可以直接修改系统的TCP最大连接时间,但是这个是极不推荐的。因为系统的修改了会影响所有运行在这台计算机上的进程,尤其是有些不活跃的进程。
参考: http://www.cnblogs.com/lidabo/p/3804108.html