package cn.xpleaf.protostuff.netty.utils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* PojoEncoder继承自Netty中的MessageToByteEncoder类,
* 并重写抽象方法encode(ChannelHandlerContext ctx, Object msg, ByteBuf out)
* 它负责将Object类型的POJO对象编码为byte数组,然后写入到ByteBuf中
*
* @author yeyonghao
*
*/
public class EchoEncoder extends MessageToByteEncoder<Object> {
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
// 直接生成序列化对象
// 需要注意的是,使用protostuff序列化时,不需要知道pojo对象的具体类型也可以进行序列化时
// 在反序列化时,只要提供序列化后的字节数组和原来pojo对象的类型即可完成反序列化
byte[] array = SerializationUtil2.serialize(msg);
out.writeBytes(array);
}
}package cn.xpleaf.protostuff.netty.utils;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
/**
* PojoDecoder继承自Netty中的MessageToMessageDecoder类,
* 并重写抽象方法decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
* 首先从数据报msg(数据类型取决于继承MessageToMessageDecoder时填写的泛型类型)中获取需要解码的byte数组
* 然后调用使用序列化工具类将其反序列化(解码)为Object对象 将解码后的对象加入到解码列表out中,这样就完成了解码操作
*
* @author yeyonghao
*
*/
public class EchoDecoder extends MessageToMessageDecoder<ByteBuf> {
// 需要反序列对象所属的类型
private Class<?> genericClass;
// 构造方法,传入需要反序列化对象的类型
public EchoDecoder(Class<?> genericClass) {
this.genericClass = genericClass;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
// ByteBuf的长度
int length = msg.readableBytes();
// 构建length长度的字节数组
byte[] array = new byte[length];
// 将ByteBuf数据复制到字节数组中
msg.readBytes(array);
// 反序列化对象
Object obj = SerializationUtil2.deserialize(array, this.genericClass);
// 添加到反序列化对象结果列表
out.add(obj);
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-83177-2.html
很棒
马云就是个大骗子吸血鬼
猪乸也会上树