- 监测数据采集物联网应用开发步骤(8.2)
TCP/IP Server开发
在com.zxy.common.Com_Para.py中添加如下内容
#锁机制
lock = threading.Lock()
#本机服务端端口已被连接客户端socket list
dServThreadList = {}
#作为服务端接收数据拦截器
ServerREFLECT_IN_CLASS = "com.plugins.usereflect.testServerReflectInClass1"
#本设备Server端口
AccSocketPort = 8090
在com.zxy.business.Analyse_Data.py类的
def SubAnalyseRecBytes函数中添加如下内容
#作为服务端接收数据拦截器elif inputIServ and Com_Para.ServerREFLECT_IN_CLASS != "":try:objC = importlib.import_module(Com_Para.ServerREFLECT_IN_CLASS) #对模块进行导入 objName = Com_Para.ServerREFLECT_IN_CLASS.split(".")objN = getattr(objC,objName[len(objName) - 1])if hasattr(objN,"strResult"):setattr(objN,"strResult",inputStrResult)setattr(objN,"strIP",inputStrIP)setattr(objN,"strPort",inputStrPort)fun_us = getattr(objN,"init_start")fun_us(objN)temResult = getattr(objN,"strResult")temSend = getattr(objN,"strSend")temContinue = getattr(objN,"strContinue")#发送到客户端数据if temSend != "":Com_Fun.SendSocket(temSend,inputMServSocket)#不继续执行操作if temContinue == "0":return ""except Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self,Com_Para.ServerREFLECT_IN_CLASS+"=1=>"+repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(Com_Para.ServerREFLECT_IN_CLASS+"=1=>"+repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息finally:pass
在com.zxy.common.Com_Fun.py中添加代码
@staticmethoddef SetThreadList(inputStrkey, inputStrValue):if Com_Para.dServThreadList is None:Com_Para.dServThreadList = {}if Com_Para.lock.acquire():Com_Para.dServThreadList[inputStrkey] = inputStrValueCom_Para.lock.release()@staticmethod def RemoveThreadList(inputStrkey):if Com_Para.lock.acquire():if Com_Para.dServThreadList.get(inputStrkey) is not None:Com_Para.dServThreadList.pop(inputStrkey)Com_Para.lock.release()
新建TCP/IP Server类com.zxy.tcp.TcpServer.py
#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''import timefrom com.zxy.business.Analyse_Data import Analyse_Data
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.z_debug import z_debug#监测数据采集物联网应用--TCP/IP Server
class TcpServer(z_debug):def __init__(self,skey):self.skey = skeydef server_link(self, sock, addr):Com_Fun.SetThreadList(self.skey, sock) while True:temInit_msg = b'' # 初始化流try:temInit_msg = sock.recv(1024*50) # 接收数据 temValue = temInit_msg.decode(Com_Para.U_CODE)if temValue == "Exit":Com_Fun.RemoveThreadList(self.skey)if sock is not None:sock.close()breakelif len(temValue) > 0:ad = Analyse_Data()ad.SubAnalyseRecBytes(temValue,sock,True, sock.getpeername()[0],str(sock.getpeername()[1]))elif temValue == "":Com_Fun.RemoveHashTable(Com_Para.dServThreadList,self.skey)if sock is not None:sock.close()breaktime.sleep(0.1)except Exception as e:Com_Fun.RemoveThreadList(self.skey)if sock is not None:sock.close()if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息Break
监测数据采集物联网应用开发步骤(9.2)