def data_received(self, data): self._buffer += data while self._buffer: if self.state == State.INIT: if len(self._buffer) < PACKET_SIZE: return msg, self._buffer = self._buffer[:PACKET_SIZE], self._buffer[ PACKET_SIZE:] try: self.packet = Packet.unpack(msg) except PacketException: logging.debug(f'failed to parse message: {msg}') self.state = State.INIT self.transport.close() return if self.packet.token != self.server.token: logging.debug(f"invalid token: {self.packet.token}") self.transport.close() logging.debug( f"cmd: {self.packet.cmd} from {self.packet.from_} to {self.packet.to}" ) self.state = State.REQUEST if self.state == State.REQUEST: if len(self._buffer) < self.packet.length: return msg, self._buffer = self._buffer[:self.packet. length], self._buffer[ self.packet.length:] self.packet.body = msg logging.debug(f"content: {self.packet.body}") command = commands.get(self.packet.cmd) or transfer self.server.loop.create_task(command(self)) self.state = State.INIT
def test_unpack(self): """ 测试解析包格式 :return: """ msg = b'\x00\x01abcdefabc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01' packet = Packet.unpack(msg) self.assertEqual(packet.ver, 1) self.assertEqual(packet.from_, 'abc') self.assertEqual(packet.to, 'abc') self.assertEqual(packet.cmd, Cmd.HEARTBEAT) self.assertEqual(packet.length, 1)
def data_received(self, data): self._buffer += data if self.state == State.INIT: if len(self._buffer) < PACKET_SIZE: return msg, self._buffer = self._buffer[:PACKET_SIZE], self._buffer[ PACKET_SIZE:] self.packet = Packet.unpack(msg) logging.info( f"cmd: {self.packet.cmd} from {self.packet.from_} to {self.packet.to}" ) self.state = State.REQUEST if self.state == State.REQUEST: if len(self._buffer) < self.packet.length: return msg, self._buffer = self._buffer[:self.packet. length], self._buffer[self.packet. length:] self.packet.body = msg logging.info(f"content: {self.packet.body}") self.state = State.INIT
def data_received(self, data): self.log.debug('received {!r}'.format(data)) packet = Packet.unpack(data) print(packet.cmd)