QTcpSocket利用setsockopt实现连接保活
保活机制
socket保活有三种机制:
- SO_KEEPALIVE
- SIO_KEEPALIVE_VALS
- Heart-Beat
Linux的keepalive机制
Linux内置支持keepalive机制,涉及三个变量:
- tcp_keepalive_time:失连时间(秒)
- tcp_keepalive_intvl:重连间隔(秒)
- tcp_keepalive_probes:重连次数(次)
查看方式:
1 | cat /proc/sys/net/ipv4/tcp_keepalive_time |
默认情况下为:
1 | 7200 |
手动设置方式(重启失效):
1 | echo 100 > /proc/sys/net/ipv4/tcp_keepalive_time |
QTcpSocket中设置keepalive
Qt提供了开启keepalive的接口,但是没有提供上述三个变量的配置接口:
1 | QTcpSocket::setSocketOption(QAbstractSocket::KeepAliveOption, 1); |
设置方式需要使用
1 | /* Set socket FD's option OPTNAME at protocol level LEVEL |
其中:
- fd: socket句柄
- level: 协议层(SOL_SOCKET、SOL_TCP)
- optname: 变量名(SO_KEEPALIVE、TCP_KEEPIDLE、TCP_KEEPINTVL、TCP_KEEPCNT)
- optval: 变量指针
- optlen: 变量长度
如使用了SO_KEEPALIVE可不设置qt自带的QAbstractSocket::KeepAliveOption
代码示例
1 |
|