package com.ard.tianyu.netty.handler;// MessageProtocolEncoder.java import com.ard.tianyu.netty.command.BaseCommand; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class MessageProtocolEncoder extends MessageToByteEncoder { @Override protected void encode(ChannelHandlerContext ctx, BaseCommand command, ByteBuf out) throws Exception { out.writeShort(command.getDataHeader()); // 写入帧头 out.writeShort(command.getDataLength()); // 写入数据长度 out.writeByte(command.getCmdCode()); // 写入指令编号 command.encode(out); // 编码具体负载 } }