编码 @param byteBuf @param packet @return
(ByteBuf byteBuf,Packet packet)
| 59 | * @return |
| 60 | */ |
| 61 | public ByteBuf encode(ByteBuf byteBuf,Packet packet) { |
| 62 | // 1. 创建ByteBuf 对象 |
| 63 | //ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer(); |
| 64 | //2. 序列化对象 |
| 65 | byte[] bytes = Serializer.DEFAULT.serialize(packet); |
| 66 | |
| 67 | //3. 实际的编码过程 |
| 68 | byteBuf.writeInt(MAGIC_NUMBER); //标识自定义协议 |
| 69 | byteBuf.writeByte(packet.getVersion()); //协议版本 |
| 70 | byteBuf.writeByte(Serializer.DEFAULT.getSerializerAlgorithm()); //序列化算法 |
| 71 | byteBuf.writeByte(packet.getCommand()); //指令 |
| 72 | byteBuf.writeInt(bytes.length); |
| 73 | byteBuf.writeBytes(bytes); //数据 |
| 74 | |
| 75 | return byteBuf; |
| 76 | } |
| 77 | |
| 78 | public Packet decode(ByteBuf byteBuf) { |
| 79 | //跳过magic number |
nothing calls this directly
no test coverage detected