乐趣区

linux keepalive探测对应用层socket api的影响

问题
大部分人都知道 tcp 的 keepalive. 假设读者知道 keepalive 会如何触发. 这篇文章想讨论 keepalive 触发后, 对 socket 使用者的影响.
keepalive 设置
修改 /etc/sysctl.conf
ubuntu# vim /etc/sysctl.conf
ubuntu# sysctl -p
fs.file-max = 131072
net.ipv4.tcp_keepalive_time = 10
net.ipv4.tcp_keepalive_intvl = 5
net.ipv4.tcp_keepalive_probes = 3
验证
ubuntu# sysctl -a | grep keepalive
net.ipv4.tcp_keepalive_intvl = 5
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_time = 10
tcp_server.py
import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = (‘localhost’, 22345)
sock.bind(server_address)
sock.listen(1)
connection, client_address = sock.accept()
while True:
data = connection.recv(1024)
print(“data”, data)
tcp_client.py
import socket
import sys
import time

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
server_address = (‘localhost’, 22345)
sock.connect(server_address)

time.sleep(999999999)

可以看到, 因为 tcp_client 开启了 SO_KEEPALIVE, 所以 tcp_client 主动往 tcp_server 发起 KEEPALIVE 探测. 若 tcp_server 开启 SO_KEEPALIVE, 则是 tcp_server 往 tcp_client 发送 KEEPALIVE 探测. 如果 tcp_server/tcp_client 都开启 KEEPALIVE, 则会双向探测.
对应用层 socket api 的影响
为了模拟 keepalive 生效的情况, 用 docker 模拟断网线的情况.
docker commit -a “enjolras” -m “ubuntu python” 92edf5cfb2e0 ubuntu_with_python
对 send/recv 的影响
对 select 的影响
对 epoll 的影响

退出移动版