简体   繁体   中英

Netty pipeline broken when adding decoder/encoder

I've recently started using netty for a project of mine. I implemented the HexDumpProxy example in order to understand how netty works. I am facing a problem when I add a StringDecoder and StringEncoder in the channel pipeline which results in a broken pipeline. If the decoder/encoder is not present the program works as it should. Can someone explain me why does this happen? Any help is highly appreciated!

Following I am adding the code.

Main class:

public final class HexDumpProxy {

public static void main(String[] args) throws Exception {

    // Configure the bootstrap.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HexDumpProxyInitializer("127.0.0.1", 9000))
         .childOption(ChannelOption.AUTO_READ, false)
         .bind(8000).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        }
    }
}

Initializer class:

public class HexDumpProxyInitializer extends ChannelInitializer<SocketChannel> {

private final String remoteHost;
private final int remotePort;

public HexDumpProxyInitializer (String remoteHost, int remotePort) {
    this.remoteHost = remoteHost;
    this.remotePort = remotePort;
}

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline().addLast("frameDecoder", new LineBasedFrameDecoder(80));
    ch.pipeline().addLast("decoder", new StringDecoder());
    ch.pipeline().addLast("encoder", new StringEncoder());
    //ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
    ch.pipeline().addLast(new HexDumpProxyFrontendHandler(remoteHost, remotePort));
    }

}

Frontend Handler class:

public class HexDumpProxyFrontendHandler extends ChannelInboundHandlerAdapter {

private final String remoteHost;
private final int remotePort;

private Channel serverChannel;

public HexDumpProxyFrontendHandler(String remoteHost, int remotePort) {
    this.remoteHost = remoteHost;
    this.remotePort = remotePort;
}

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel clientChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(clientChannel.eventLoop())
     .channel(ctx.channel().getClass())
     .handler(new HexDumpProxyBackendHandler(clientChannel))
     .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    serverChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                clientChannel.read();
            }
            else
                clientChannel.close();
            }

        });
}

@Override
public void channelRead (final ChannelHandlerContext ctx, Object msg) {
    if (serverChannel.isActive()) {
        System.out.println("************" + msg);
        serverChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                    System.out.println("Read from server channel. - channelRead");
                } else {
                    future.channel().close();
                    System.out.println("Close server channel.");
                }
            }
        });
    }
}

@Override
public void channelInactive (ChannelHandlerContext ctx) {
    if (serverChannel != null) {
        closeOnFlush(serverChannel);
        System.out.println("close on flush - server channel");
    }
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
}

static void closeOnFlush (Channel ch) {
    if (ch.isActive())
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
    ctx.channel().read();
    }
}

Backend Handler class:

public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter {

private final Channel clientChannel;

public HexDumpProxyBackendHandler (Channel clientChannel) {
    this.clientChannel = clientChannel;
}

@Override
public void channelActive (ChannelHandlerContext ctx) {
    ctx.channel().read();
    System.out.println("Read from client channel. - channelActive");
}

@Override
public void channelRead (final ChannelHandlerContext ctx, Object msg) {
    System.out.println("~~~~~~~~~~~" + msg);
    clientChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                clientChannel.read();
                System.out.println("Read from client channel. - channelRead");
            } else {
                clientChannel.close();
                System.out.println("Close client channel.");
                }
            }
        });
}

@Override
public void channelInactive (ChannelHandlerContext ctx) {
    HexDumpProxyFrontendHandler.closeOnFlush(clientChannel);
    System.out.println("close on flush - client channel");
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
    ctx.channel().read();
    }
}

For everyone in the future that will face a similar problem, I found where the problem was.

In class HexDumpProxyFrontendHandler instead of using new HexDumpProxyBackendHandler(clientChannel) as a handler during the bootstrap, create a new class eg HexDumpProxyBackendInitializer(clientChannel) and in the class initialize the pipeline in the same way as in the class HexDumpProxyInitializer .

Hope this can help someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM