/** * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next * {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. */ publicbooleanacceptOutboundMessage(Object msg)throws Exception { return matcher.match(msg); }
// 如果未编码出消息,抛出异常 if (out.isEmpty()) { // 回收 CodecOutputList 对象 out.recycle(); out = null; // 抛出异常 thrownew EncoderException(StringUtil.simpleClassName(this) + " must produce at least one message."); } } else { // 直接下一个节点 ctx.write(msg, promise); } } catch (EncoderException e) { throw e; } catch (Throwable t) { thrownew EncoderException(t); } finally { if (out != null) { finalint sizeMinusOne = out.size() - 1; // 只编码出一条消息 if (sizeMinusOne == 0) { // 直接写入新消息到下一个节点 ctx.write(out.get(0), promise); // 编码出多条消息 } elseif (sizeMinusOne > 0) { // 第 [0, n-1) 条消息,写入下一个节点,使用 voidPromise ,即不需要回调 // Check if we can use a voidPromise for our extra writes to reduce GC-Pressure // See https://github.com/netty/netty/issues/2525 ChannelPromise voidPromise = ctx.voidPromise(); boolean isVoidPromise = promise == voidPromise; for (int i = 0; i < sizeMinusOne; i ++) { ChannelPromise p; if (isVoidPromise) { p = voidPromise; } else { p = ctx.newPromise(); } ctx.write(out.getUnsafe(i), p); } // 第 n-1 条消息,写入下一个节点,使用 promise ,即需要回调 ctx.write(out.getUnsafe(sizeMinusOne), promise); } // 回收 CodecOutputList 对象 out.recycle(); } } }
代码比较简单,胖友自己看注释。
2.4 encode
/** * Encode from one message to an other. This method will be called for each written message that can be handled * by this encoder. * * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToMessageEncoder} belongs to * @param msg the message to encode to an other one * @param out the {@link List} into which the encoded msg should be added * needs to do some kind of aggregation * @throws Exception is thrown if an error occurs */ protectedabstractvoidencode(ChannelHandlerContext ctx, I msg, List<Object> out)throws Exception;
/** * Decode from one message to an other. This method will be called for each written message that can be handled * by this encoder. * * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to * @param msg the message to decode to an other one * @param out the {@link List} to which decoded messages should be added * @throws Exception is thrown if an error occurs */ protectedabstractvoiddecode(ChannelHandlerContext ctx, I msg, List<Object> out)throws Exception;
/** * Returns {@code true} if and only if the specified message can be decoded by this codec. * * @param msg the message */ publicbooleanacceptInboundMessage(Object msg)throws Exception { return inboundMsgMatcher.match(msg); }
/** * Returns {@code true} if and only if the specified message can be encoded by this codec. * * @param msg the message */ publicbooleanacceptOutboundMessage(Object msg)throws Exception { return outboundMsgMatcher.match(msg); }