2024-07-31 16:48:29 +08:00
|
|
|
|
package rpc;
|
|
|
|
|
|
|
2024-07-31 17:14:41 +08:00
|
|
|
|
import com.jsowell.common.util.bean.SerializationUtil;
|
2024-07-31 16:48:29 +08:00
|
|
|
|
import io.netty.buffer.ByteBuf;
|
|
|
|
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
|
|
|
|
import io.netty.handler.codec.MessageToByteEncoder;
|
|
|
|
|
|
|
|
|
|
|
|
public class MessageEncode extends MessageToByteEncoder<Message> {
|
|
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
|
protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
|
|
|
|
|
|
// 将对象进行序列化
|
|
|
|
|
|
byte[] data = SerializationUtil.serialize(message);
|
|
|
|
|
|
|
|
|
|
|
|
// 写数据长度,前4个字节用于记录数据总长度(对象 + 类型(1个字节))
|
|
|
|
|
|
byteBuf.writeInt(data.length + 1);
|
|
|
|
|
|
// 写记录消息类型,用于反序列选择类的类型
|
|
|
|
|
|
byteBuf.writeByte(message.getMessageType());
|
|
|
|
|
|
// 写对象
|
|
|
|
|
|
byteBuf.writeBytes(data);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|