package com.jsowell.netty.decoder; import com.jsowell.common.protocol.Message; import com.jsowell.common.util.bean.SerializationUtil; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class MessageEncode extends MessageToByteEncoder { @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); } }