开启keepalive 策略:
我们通常需要调整触发 KeepAlive 的 idle 时间间隔:
s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 10)
最后一个参数 10 表示在连接不活跃 10s 后开始 KeepAlive 检测。
s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 6)
最后一个参数表示每隔 6s 发送一次。
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
09:12:44.562557 IP node2.62703 > node1.webcache: Flags [.], ack 2734275117, win 115, options [nop,nop,TS val 129479501 ecr 2309184], length 0
09:12:46.562941 IP node2.62703 > node1.webcache: Flags [.], ack 2734275117, win 115, options [nop,nop,TS val 129481501 ecr 2309184], length 0
09:12:48.564049 IP node2.62703 > node1.webcache: Flags [.], ack 2734275117, win 115, options [nop,nop,TS val 129483502 ecr 2309184], length 0
09:12:50.564471 IP node2.62703 > node1.webcache: Flags [R.], seq 4113924244, ack 2734275117, win 115, options [nop,nop,TS val 129485503 ecr 2309184], length 0
node2:/root/test#cat t17.py
import socket
import IN
import struct
import time
b=2
def getnum(x):
b='2'
for y in range(x):
#print y
b=b+'2'
if len(b) == x:
#print '-------------'
#print len(b)
return b
print getnum(1024)
c=getnum(1460)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#class IN:
# IP_MTU = 14
# IP_PMTUDISC_DONT = 0
# IP_PMTUDISC_DO = 2
# IP_MTU_DISCOVER=10
#s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#s.setsockopt(socket.IPPROTO_IP, IN.IP_MTU_DISCOVER,IN.IP_PMTUDISC_DONT)
# print dir(s.setsockopt(socket.SOL_SOCKET))
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 10)
s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 2)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
s.connect(("192.168.137.2",8080))
print len(c)
s.send(c)
#option = getattr(IN, 'IP_MTU_DISCOVER', 10)
#print 'MTU:', s.getsockopt(socket.IPPROTO_IP, option)
time.sleep(2000)
s.close()
node2:/root/test#cat test.py
import socket
import time
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(17)
s.connect(("1.1.1.2",9090))
print s.getsockname()
print s.getpeername()
发三次,间隔2秒 ,重试次数3次