import socket import struct # 初始化socket对象 def initialSocket(self): self.WrtLog('开始连接服务端...') try: self.tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_client_socket.connect((host, port)) # 连接 self.WrtLog('连接成功.') except Exception as ex1: self.WrtLog('连接失败:'+str(ex1)) # 监听服务端发送过来的消息 def fnConnectServer(self): self.initialSocket() while True: msg = self.fnSockGetMsg(self.tcp_client_socket) self.WrtLog('服务端发来消息:'+msg) # 停止 def fnStopServer(self): self.WrtLog('关闭连接...') msg = 'qt_quit' try: self.fnSockSendMsg(self.tcp_client_socket, msg) self.tcp_client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 释放socket对象 self.WrtLog('释放连接完成') except Exception as ex1: self.WrtLog(str(ex1)) # 发送消息,处理粘包 def fnSockSendMsg(self, conn, msg): msg = msg.encode('utf-8') dataHead = struct.pack('i', len(msg)) # 把消息长度打包成固定长度的bytes conn.send(dataHead) # 发送包头 conn.send(msg) # 发送消息 # 获取消息,处理粘包 def fnSockGetMsg(self, conn): dataHead = conn.recv(4) # 先获取包头 dataLen = struct.unpack('i', dataHead)[0] # 把包头解包成int类型 # 开始读取长度为 dataLen 的数据 recData = b'' # 获取到的消息 cacheLen = 1024 # 缓冲区大小 page = dataLen // cacheLen # 分片 if page > 0: for i in range(page): recData += conn.recv(cacheLen) pageEnd = dataLen % cacheLen # 最后一片 recData += conn.recv(pageEnd) else: recData += conn.recv(dataLen) msg = recData.decode('utf-8') return msg