在很多网络应用程序,需要自定义心跳包来保持连接,不然断电或者非法关闭程序,对方识别不到,需要进行超时检测,但是有些程序没有提供心跳协议,此时需要启用系统层的保活程序,此方法适用于TCP连接。
int fd = tcpSocket->socketDescriptor();
int keepAlive = 1; //开启keepalive属性,缺省值:0(关闭)
int keepIdle = 5; //如果在5秒内没有任何数据交互,则进行探测,缺省值:7200(s)
int keepInterval = 2; //探测时发探测包的时间间隔为2秒,缺省值:75(s)
int keepCount = 2; //探测重试的次数,全部超时则认定连接失效,缺省值:9(次)
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive));
setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle));
setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
|