在Netty编码器中获得Stackoverflow

时间:2018-10-14 18:01:01

标签: java netty

我想在发送实际消息之前发送自己的自定义消息,这是第一次初始化频道。我有:

public class MyClientInitializerFactory extends ClientInitializerFactory {

@Override
protected void initChannel(Channel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new EncoderTwo());
    pipeline.addLast(new EncoderOne());
}
}

EncoderOne:

public class EncoderOne extends MessageToMessageEncoder<Object> {

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    byte[] bytes = "ABCD".getBytes(StandardCharsets.UTF_8);
    ByteBuf byteBuf = Unpooled.buffer(bytes.length);
    Channel channel = ctx.channel();
    channel.writeAndFlush(byteBuf);
    out.add(msg); // retaining original message for further processing
    ctx.pipeline().remove(this);
}

EncoderTwo处理实际消息并将其通过电线发送,但我的消息从未到达那里。当我尝试发送任何内容时,这些行会一遍又一遍地执行,直到得到StackOverflow:

 ByteBuf byteBuf = Unpooled.buffer(bytes.length);
 Channel channel = ctx.channel();
 channel.writeAndFlush(byteBuf);

我该怎么办?

1 个答案:

答案 0 :(得分:2)

问题是您在编码器中调用channel.writeAndFlush(byteBuf);,这意味着它将再次从尾部开始流过管道,从而再次进入编码器。因此,请先移除编码器再调用它,或致电ctx.writeAndFlush(...)

一种替代方法是也将byteBuf直接添加到外部List中,然后再调用flush()