def writeDouble(self, obj): try: if type(obj) is not float: return self.data += struct.pack('<d', obj) except Exception as e: LogCat.log('Packet.py-SendPacket().writeDouble', type(e), e)
def writeUInt(self, obj): try: if type(obj) is not int: return self.data += struct.pack('<I', obj) except Exception as e: LogCat.log('Packet.py-SendPacket().writeUInt', type(e), e)
def send(client, data): try: if showSendPacket: print('SendData : ', client.getpeername(), ':', data) client.send(bytes(data, encoding="utf-8")) except Exception as e: LogCat.log('(심각)sendPacket.py-SendPacket().send', type(e), e)
def makeInt(self, obj): try: if type(obj) is not int: return return struct.pack('<i', obj) except Exception as e: LogCat.log('Packet.py-SendPacket().makeInt', type(e), e)
def writeString(self, obj): try: if type(obj) is not str: return self.writeInt(SendPacket.getStringSize(obj)) self.data += obj.encode() except Exception as e: LogCat.log('Packet.py-SendPacket().writeString', type(e), e)
def writeByte(self, obj): try: if type(obj) is not bytes: return self.writeInt(len(obj)) self.data += obj except Exception as e: LogCat.log('Packet.py-SendPacket().writeByte', type(e), e)
def readDouble(self): try: if self.ableRead(8): self.pos += 8 return struct.unpack('d', self.data[self.pos - 8:self.pos])[0] else: return None except Exception as e: LogCat.log('Packet.py-ReadPacket().readDouble', type(e), e)
def __init__(self, bytedata=bytes()): try: if type(bytedata) is SendPacket: self.data = bytedata.data elif type(bytedata) is bytes: self.data = bytedata self.maxlen = len(self.data) + 1 self.pos = 0 except Exception as e: LogCat.log('Packet.py-ReadPacket().__init__', type(e), e)
def readString(self): try: size = self.readInt() if self.ableRead(size): self.pos += size return self.data[self.pos - size:self.pos].decode('utf-8') else: self.pos += 4 return None except Exception as e: LogCat.log('Packet.py-ReadPacket().readString', type(e), e)
def readByte(self): try: size = self.readInt() if self.ableRead(size): self.pos += size return self.data[self.pos - size:self.pos] else: self.pos += 4 return None except Exception as e: LogCat.log('Packet.py-ReadPacket().readByte', type(e), e)
def readShort(self): try: if self.ableRead(2): self.pos += 2 return int.from_bytes(self.data[self.pos - 2:self.pos], byteorder='little', signed=True) else: return None except Exception as e: LogCat.log('Packet.py-ReadPacket().readShort', type(e), e)
def readUInt(self): try: if self.ableRead(4): self.pos += 4 return int.from_bytes(self.data[self.pos - 4:self.pos], byteorder='little', signed=False) else: return None except Exception as e: LogCat.log('Packet.py-ReadPacket().readUInt', type(e), e)
def write(self, obj): try: if type(obj) == int: self.writeInt(obj) elif type(obj) == float: self.writeDouble(obj) elif type(obj) == str: self.writeString(obj) elif type(obj) == bytes: self.writeByte(obj) else: raise Exception('지원하지 않는 데이터입니다.') except Exception as e: LogCat.log('Packet.py-SendPacket().write', type(e), e)
def serverThread(PORT, WORKERS): try: cnt = 0 server = Server(PORT=PORT, WORKERS=WORKERS) while not server.openServer(): cnt += 1 print('서버설정에 실패하였습니다.', PORT, ' 재시도중', cnt) time.sleep(3) # 서버개방 실패시, 재오픈까지의 시간 print('포트개방 PORT =', PORT) server.recvUser() del server except Exception as e: LogCat.log('(심각)main.py-main().serverThread', type(e), e)
def send(self): try: self.data = self.makeInt(len(self.data)) + self.data sendlen = self.client.send(self.data) if showSendPacket: print(sendlen, '|SendData :', self.client.getpeername(), ':', end='') for i in self.data: print(i, end=' ') print() except Exception as e: LogCat.log('Packet.py-SendPacket().send', type(e), e)
def recvdata(socket, fd, bytedata): try: client = socket[fd] packet = ReadPacket(bytedata) opcode = packet.readShort() if opcode == OpCodeData.login_id: # 로그인요청 Account.login_id(client, packet) elif opcode == OpCodeData.login_email: Account.login_email(client, packet) else: print(opcode, 'no Opcode') except ConnectionResetError: raise ConnectionResetError() except Exception as e: LogCat.log('(심각)Opcode.py-Server().recvUser', type(e), e)
def recvUser(self): global fdmap while True: events = self.epoll.poll() for fd, event in events: if fd is self.socket.fileno(): try: self.c, addr = self.socket.accept() self.c.setblocking(0) self.epoll.register(self.c) fdmap[self.c.fileno()] = self.c print(self.c.getsockname()[1], 'PORT :', fd, '서버에 접속됨 : ', addr) except Exception as e: LogCat.log( '(심각)ServerConstant.py-Server().recvUser-if fd is fileno()', type(e), e) elif event & select.EPOLLIN: try: data = fdmap[fd].recv(1024) #data = fdmap[fd].recv(8192, socket.MSG_WAITALL) if not data: #접속 종료시 이상한 데이터가 들어옴 print('PORT :', self.c.getsockname()[1], fd, '클라이언트에서 접속 종료함') self.epoll.unregister(fd) del fdmap[fd] exitClient(fd) else: if showRecvPacket: print('RecvData :', data) self.executor.submit(Opcode.recvdata, fdmap, fd, data) except ConnectionResetError: #비정상적인 종료 print('[경고]PORT :', self.c.getsockname()[1], fd, '클라이언트에서 접속 종료함') self.epoll.unregister(fd) del fdmap[fd] exitClient(fd) except Exception as e: LogCat.log('(심각)ServerConstant.py-Server().recvUser', type(e), e)
def openServer(self): global fdmap try: self.socket.bind((self.HOST, self.PORT)) self.socket.listen(10) self.socket.setblocking(False) fdmap = {self.socket.fileno(): self.socket} self.epoll = select.epoll() self.epoll.register(self.socket) return True except OSError as e: if str(e) != '[Errno 98] Address already in use': LogCat.log('(문제)ServerConstant.py-Server().openServer', type(e), e) return False except Exception as e: LogCat.log('(문제)ServerConstant.py-Server().openServer', type(e), e) return False
def __init__(self, client): try: self.client = client self.data = bytes() except Exception as e: LogCat.log('Packet.py-SendPacket().__init__', type(e), e)
def __del__(self): try: self.executor.shutdown() except Exception as e: LogCat.log('ServerCpmstamt.py-Server().__del__', type(e), e)
def ableRead(self, size): try: return self.pos + size < self.maxlen except Exception as e: LogCat.log('Packet.py-ReadPacket().ableRead', type(e), e) return None
def exitClient(fd): try: pass except Exception as e: LogCat.log('(심각)ServerConstant.py-noClass().exitClient', type(e), e)
def dbClear(): try: pass except Exception as e: LogCat.log('(심각)main.py-main().dbClear', type(e), e)
threadlist.append(thread) # 추후 Thread관리 시 필요한 목록 time.sleep(0.001) while True: str = input("명령어 입력") if str == 'q': sys.exit(0) if __name__ == "__main__": try: main() except KeyboardInterrupt: 1 except Exception as e: LogCat.log('(매우심각)main.py-main', type(e), e) ''' MYSQL Using Giude(del 쓰면 알아서 closeSQL호출) from database.MySQLConnection import MySQL mysql = MySQL() if mysql.connectSQL(): print(mysql.executeSQL('SQL')) mysql.closeSQL() else: print('fail sql connect') del mysql Server Open Guide from serverConstants.ServerConstant import Server server = Server(PORT=,WOKERS=) if server.openServer():
def __str__(self): try: return self.data.__str__() except Exception as e: LogCat.log('Packet.py-SendPacket().__str__', type(e), e) return None
def getStringSize(data): try: data = data.encode() return len(data) except Exception as e: LogCat.log('Packet.py-SendPacket().getStringSize', type(e), e)
def getData(self): try: return self.data except Exception as e: LogCat.log('Packet.py-SendPacket().getData', type(e), e) return bytes()