import socket import sys import threading import time import log import app class tcp_param: def __init__(self): self.host = 'localhost' self.port = 56926 self.buffsize = 128 self.rd_data = '' self.wr_data = '' self.wr_stat = False tcpserverParam = tcp_param() class socket_server(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter self.user_var = app.user_var self.tcpserverParam = tcpserverParam # 获取本地主机名 self.tcpserverParam.host = '127.0.0.1' self.BUFSIZE = self.tcpserverParam .buffsize # 创建 socket 对象 self.serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # 绑定端口号 self.serversocket.bind((self.tcpserverParam.host, self.tcpserverParam.port)) self.exit_stat = False self.exit_ok = False self.log_file = log.log_file self.log_print = log.log_file def exit(self): self.exit_stat = True def run(self): # 设置最大连接数,超过后排队 self.serversocket.listen(5) while self.exit_stat == False: try: print('waiting for connection...') self.serversocket.settimeout(10) clientsocket, addr = self.serversocket.accept() print(addr) self.serversocket.settimeout(300) self.user_var.socket_conn_stat = True while self.exit_stat == False: if self.tcpserverParam.wr_stat == True: try: print('waiting for recv') msg = clientsocket.recv(18).decode("ascii") print(msg) if msg == 'TCP:Give me string': # time.sleep(2) size = clientsocket.send(self.tcpserverParam.wr_data.encode("ascii")) self.tcpserverParam.wr_stat = False self.log_print.logger.info('tcpsend={0}'.format(size), stack_info=True) except ConnectionResetError as e: self.log_file.logger.error('socket连接: {0}'.format(e), exc_info=True, stack_info=True) break except Exception as e: self.log_file.logger.error('socket未知异常: {0}'.format(e), exc_info=True, stack_info=True) break time.sleep(0.1) clientsocket.close() except socket.error as e: print("客户端断开!") except ConnectionResetError as e: self.log_file.logger.error('socket连接: {0}'.format(e), exc_info=True, stack_info=True) except Exception as e: self.log_file.logger.error('socket未知异常: {0}'.format(e), exc_info=True, stack_info=True) self.user_var.socket_conn_stat = False print("socket进程结束!")