前言
上一篇我们讲解了解码器的相关知识,其中也提到了编码器的定义。
Netty 源码分析系列(十二)Netty 解码器
编码器就是用来把出站数据从一种格式转换到另外一种格式,因此它实现了ChannelOutboundHandler,类似于解码器,Netty 也提供了一组类来帮助开发者快速上手编码器,当然,这些类提供的是与解码器相反的方法,如下所示:
- 编码从消息到字节(MessageToByteEncoder)。
- 编码从消息到消息(MessageToMessageEncoder)。
MessageToByteEncoder 抽象类
在上一篇文章中,我们知道了如何使用ByteToMessageDecoder来将字节转换成消息,现在可以使用MessageToByteEncoder实现相反的效果。
MessageToByteEncoder 核心代码如下:
public abstract class MessageToByteEncoder<I> extends ChannelOutboundHandlerAdapter {
private final TypeParameterMatcher matcher;
private final boolean preferDirect;
protected MessageToByteEncoder() {
this(true);
}
protected MessageToByteEncoder(Class<? extends I> outboundMessageType) {
this(outboundMessageType, true);
}
protected MessageToByteEncoder(boolean preferDirect) {
this.matcher = TypeParameterMatcher.find(this, MessageToByteEncoder.class, "I");
this.preferDirect = preferDirect;
}
protected MessageToByteEncoder(Class<? extends I> outboundMessageType, boolean preferDirect) {
this.matcher = TypeParameterMatcher.get(outboundMessageType);
this.preferDirect = preferDirect;
}
public boolean acceptOutboundMessage(Object msg) throws Exception {
return this.matcher.match(msg);
}
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ByteBuf buf = null;
try {
if (this.acceptOutboundMessage(msg)) {
I cast = msg;
buf = this.allocateBuffer(ctx, msg, thi