网上找到一段代码 关于 socketserver 的使用
本来想用C++ 和 libevent 写,libevent 对linux 支持的很好,macos 支持的也可以,但是windows 有点不太尽如人意,Qt 框架的 又得被迫开源一些东西,也很烦
先用python 写一个示例,先凑合着用
import socketserverclass MyServer(socketserver.BaseRequestHandler):def handle(self):conn = self.requesttry:conn.sendall("good?".encode())Flag = Truewhile Flag:data = conn.recv(1024)if data == "exit":Flag = Falseelif data == "0":conn.sendall("verygood?".encode())else:conn.sendall("goodgood?".encode())except:print("Okay I will close connect")conn.close()if __name__ == "__main__":server = socketserver.ThreadingTCPServer(("127.0.0.1", 40000), MyServer)server.serve_forever()
server example 有一些问题
需要重写一个 TCP SERVER 的基类重新,构造ThreadTcpServer 和 ThreadUdpServer
import socketserver
import logging
import socket
from enum import Enumclass NetWorkTransType(Enum):TCP = 0x1UDP = 0x2class NetWorkWorkType(Enum):CLIENT = 0x1SERVER = 0x2class NetWorkCFG:ip: strport: inttransType: NetWorkTransTypeworkType: NetWorkWorkTypedef __init__(self, ip: str, port: int, transType: NetWorkTransType, workType: NetWorkWorkType):self.ip = ipself.port = portself.transType = transTypeself.workType = workTypeclass NetWorkHandle(socketserver.BaseRequestHandler):__heartbeat_en__ = False__readwrite_en__ = False__alarm_en__ = False__call_heartbeat__ = None__call_readwrite__ = None__call_alarm__ = None__trans_flag__: NetWorkTransType__login_en__ = False__call_login__ = Nonedef setTransFlag(self, flag: NetWorkTransType):self.__trans_flag__ = flagdef handle(self) -> None:conn = self.requestrecvDATA = b"\x00"sendDATA = b"\x00"status = Falsetry:if self.__trans_flag__ == NetWorkTransType.TCP:recvDATA = conn.recv(4096)elif self.__trans_flag__ == NetWorkTransType.UDP:recvDATA, _ = conn[0].recvfrom(4096)while True:if self.__login_en__ and self.__call_login__ is not None:status, sendDATA = self.__call_login__(recvDATA)if status is True:breakif self.__heartbeat_en__ and self.__call_heartbeat__ is not None:# positivate recv heartbeatstatus, sendDATA = self.__call_heartbeat__(recvDATA)if self.__alarm_en__ and self.__call_alarm__ is not None:status, sendDATA = self.__call_alarm__(recvDATA)if self.__readwrite_en__ and self.__call_readwrite__ is not None:status, sendDATA = self.__call_readwrite__(recvDATA)breakif self.__trans_flag__ == NetWorkTransType.TCP:conn.sendall(sendDATA)elif self.__trans_flag__ == NetWorkTransType.UDP:conn[0].sendto(sendDATA, conn[1])except (ConnectionResetError,ConnectionRefusedError,ConnectionAbortedError,ConnectionError,) as err:if self.__trans_flag__ == NetWorkTransType.TCP:logging.error("%s:%s" % (self.client_address[0], err.strerror))conn.close()elif self.__trans_flag__ == NetWorkTransType.UDP:logging.error("%s:%s" % conn[1], err.strerror)conn[0].close()# enable alarm threaddef alarmEnable(self, enable: bool):self.__alarm_en__ = enable# enable readwrite threaddef readwriteEnable(self, enable: bool):self.__readwrite_en__ = enable# enable hearbeat threaddef hearbeatEnable(self, enable: bool):self.__heartbeat_en__ = enabledef set_callHeartBeat(self, func):self.__call_heartbeat__ = funcdef set_callReadWrite(self, func):self.__call_readwrite__ = funcdef set_callAlarm(self, func):self.__call_alarm__ = funcdef set_callLogin(self, func):self.__call_login__ = funcdef loginEnable(self, enable: bool):self.__login_en__ = enableclass NetWork:__heartbeat_en__ = False__readwrite_en__ = False__alarm_en__ = False__config__: NetWorkCFG__call_heartbeat__ = None__call_readwrite__ = None__call_alarm__ = None__handle__ = None__server__ = None__login_en__ = False__call_login__ = Falsedef __init__(self, config: NetWorkCFG):self.__config__ = configdef overrideNETWORK_CFG(self, config: NetWorkCFG):self.__config__ = configdef set_callHeartBeat(self, func):self.__call_heartbeat__ = funcdef set_callReadWrite(self, func):self.__call_readwrite__ = funcdef set_callAlarm(self, func):self.__call_alarm__ = funcdef set_callLogin(self, func):self.__call_login__ = funcdef loginEnable(self, enable: bool):self.__login_en__ = enable# enable alarm threaddef alarmEnable(self, enable: bool):self.__alarm_en__ = enable# enable readwrite threaddef readwriteEnable(self, enable: bool):self.__readwrite_en__ = enable# enable hearbeat threaddef hearbeatEnable(self, enable: bool):self.__heartbeat_en__ = enabledef setHandle(self, handle):self.__handle__ = handledef GETtransType(self):return self.__config__.transTypedef GETworkType(self):return self.__config__.workType# TODO: client work will adddef start(self):if self.__handle__ is None:returnif self.__config__.transType == NetWorkTransType.TCP:if self.__config__.workType == NetWorkWorkType.SERVER:self.__server__ = socketserver.ThreadingTCPServer((self.__config__.ip, self.__config__.port), self.__handle__)elif self.__config__.workType == NetWorkWorkType.CLIENT:passelif self.__config__.transType == NetWorkTransType.UDP:if self.__config__.workType == NetWorkWorkType.SERVER:self.__server__ = socketserver.ThreadingUDPServer((self.__config__.ip, self.__config__.port), self.__handle__)elif self.__config__.workType == NetWorkWorkType.CLIENT:passif self.__server__ is not None:self.__server__.serve_forever()
修改方法