From 211b879a75dd4f8df5e9aa520221c9ebdadc7408 Mon Sep 17 00:00:00 2001 From: murmur Date: Sat, 11 Mar 2023 11:51:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BC=93=E5=AD=98=E6=9C=BA?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server.py | 71 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 10 deletions(-) diff --git a/server.py b/server.py index 35a1bee..6c67619 100644 --- a/server.py +++ b/server.py @@ -2,15 +2,39 @@ #coding:utf-8 import socketserver import subprocess +import pickle + + + offs = 0 #偏移量 p ={} #保存终端信息,ccid与地址对 #p={ccid=addr,} #缓存未能正常发送消息的客户端 pp={} -cache=[] +# cache={} +from collections import defaultdict +cache=defaultdict(list) +def save_cache(dic): + '''缓存未发送成功的消息''' + + # f=open("./cache.txt",mode='w+') + # f.write(str(dic)) + # f.close + pickle.dump(dic,open("./cache.txt",'wb')) + +def load_cache(): + try: + # f=open("./cache.txt") + # c = eval(f.read()) + # f.close() + c=pickle.load(open("./cache.txt",'rb')) + return c + except: + return None + def update_pairs(addr,ccid,clear=0): '''更新终端库 addr:绑定tcp地址 @@ -59,13 +83,25 @@ def get_ccid(addr): +--------+--------------+----------+----------+--------------+------------------------+--------+ ''' +def send(fd,data): + try: + fd.send(data) + return 0 + except: + return -1 + def tt_hh(addr,data): '''处理心跳''' # 更新pairs - update_pairs(addr,data[7+offs:11+offs]) + ccid = data[7+offs:11+offs] + update_pairs(addr,ccid) # 组帧再返回 + # 从缓存中匹配数据并重发 + if ccid in cache: + for i in cache[ccid]: + addr.send(i) return 0 @@ -74,27 +110,37 @@ def tt_trans(addr,data): tccid = data[7+offs:11+offs] taddr = get_addr(tccid) - if not taddr: - print("未找到在线终端,可能终端未在线或ccid错。") - return 0 - print("找到匹配终端:",tccid,"<--->",taddr) # 组帧 msg = bytearray(data[:]) - msg[:5]=b'$TMMX' + msg[:5]=b'$TTMX' msg[7+offs:11+offs] = get_ccid(addr) # 计算校验和 crc = 0 - for i in msg[:-2]: + for i in msg[:-1]: crc = crc ^ i msg[-1]=crc + if not taddr: + #更新缓存 + #{tccid1=[msg1,msg2,...],...} + cache[tccid].append(msg) + save_cache(cache) + print("未找到在线终端,可能终端未在线或ccid错。") + return 0 + print("找到匹配终端:",tccid,"<--->",taddr) + + # 发送 try: taddr.send(msg) except Exception: - # 更新pairs + # 更新pairs,清空对应终端 update_pairs(taddr,tccid,1) + #更新缓存 + #{tccid1=[msg1,msg2,...],...} + cache[tccid].append(msg) + save_cache(cache) print("终端已掉线。",taddr) return 0 @@ -114,7 +160,7 @@ def tt_decode(addr,data): '''处理收到的数据''' - if data[:5].hex() != "2454544d53" or len(data) <12: + if data[:5] != b'$TTMS' or len(data) <12: # 数据长度不可能小于12,考虑非法接入的可能,主动断开连接 return -1 @@ -151,8 +197,13 @@ class MyServer(socketserver.BaseRequestHandler): if __name__ == '__main__': + # load_cache + cache = load_cache() + server = socketserver.ThreadingTCPServer(('localhost',8005), MyServer) ip, port = server.server_address print ("服务端已建立:",ip, port) server.serve_forever() + +