服务器和代理服务器之间的连接添加心跳机制

This commit is contained in:
ranchuan
2024-10-09 11:10:16 +08:00
parent 3e4d145920
commit 7cabaa0479
3 changed files with 45 additions and 17 deletions

View File

@@ -31,8 +31,8 @@ _local_client=[]
# LOCAL_SERVER_IP = ("192.168.3.166",80)
# LOCAL_SERVER_IP = ("192.168.3.167",22)
LOCAL_SERVER_IP = ("192.168.3.174",22)
LOCAL_SERVER_IP = ("192.168.1.40",22)
# LOCAL_SERVER_IP = ("192.168.3.174",22)
@@ -69,16 +69,27 @@ def close_all():
myprint('连接列表已清空')
_tick_start:float=0
_tick_end:float=0
# 定时任务
def remote_keeplive():
cmd={'device':'server','option':'login'}
global _tick_start
global _tick_end
cmd={'device':'server','option':'keeplive'}
data=pc.encode(json.dumps(cmd).encode('utf-8'),b'default')
try:
_remote_client.send(data)
except Exception as e:
myprint(str(e))
_tick_end=time.perf_counter()
# 超过15秒没收到数据则自动断开
if(_tick_end-_tick_start>15):
myprint("长时间没收到代理服务器的数据回复,主动断开连接")
try:
_remote_client.close()
except Exception as e:
myprint(str(e))
@@ -122,9 +133,10 @@ def local_client_handler(tcp_server:socket.socket,ip,port):
# 远端数据处理,解包,把负载数据发送到本地服务器
def remote_client_handler(tcp_client_1:socket.socket):
def remote_client_handler(tcp_client:socket.socket):
global _remote_client
global _local_client
global _tick_start
myprint("已连接代理服务器")
timer=threading.Timer(5,remote_keeplive,())
cmd={'device':'server','option':'login'}
@@ -132,15 +144,18 @@ def remote_client_handler(tcp_client_1:socket.socket):
_remote_client.send(data)
timer.start()
recv_data=bytearray()
_tick_start=time.perf_counter()
while True:
try:
recv = tcp_client_1.recv(4096)
recv = tcp_client.recv(4096)
except Exception as e:
myprint("remote:",str(e))
break
if recv:
timer.cancel()
timer=threading.Timer(5,remote_keeplive,())
timer.start()
_tick_start=time.perf_counter()
recv_data+=recv
while True:
start=recv_data.find(b'\xff')
@@ -168,6 +183,8 @@ def remote_client_handler(tcp_client_1:socket.socket):
if(j['option']=='close'):
myprint("收到代理服务器的断开通知")
close_all()
elif(j["option"]=='keeplive'):
myprint("收到代理服务器的心跳数据")
except Exception as e:
myprint(str(e))
recv_data=recv_data[end+1:]
@@ -175,7 +192,10 @@ def remote_client_handler(tcp_client_1:socket.socket):
break
timer.cancel()
timer.join()
tcp_client_1.close()
try:
tcp_client.close()
except Exception as e:
myprint(str(e))
myprint("与代理服务器的连接已断开")
close_all()