Jeremy Umansky
Jeremy Umansky

Reputation: 31

Adding Netty Handler after Channel Initialization: Netty 4.0.17.Final

I create a NettyServer with a channelInitializer that sets up the pipeline in the initChannel method. I then call

b.bindPort(port).sync().channel().pipeline().addLast(handler).

The handler gets added before the pipeline gets initialized, I guess because the sync only waits for the channel to be created.

The question is, how do I add a handler to the end of the pipeline after the pipeline has already been initialized?

Also, how do I ensure that the last handler is added before any message is received by the server?

Thanks.

Upvotes: 2

Views: 3472

Answers (1)

paziwatts
paziwatts

Reputation: 98

The book Netty in Action has the following points:

You can add multiple handlers in the initialiser:

    @Override
    protected void initChannel(Channel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();
      if (client) {
          pipeline.addLast("codec", new HttpClientCodec());
      } else {
          pipeline.addLast("codec", new HttpServerCodec());
      }
      pipeline.addLast("aggegator",
        new HttpObjectAggregator(512 * 1024));
    }

Modifications on the ChannelPipeline can be done on-the-fly, which means you can add/remove/replace ChannelHandler even from within another ChannelHandler or have it remove itself. This allows writing flexible logic, such as multiplexer

When you add handlers later you can store the ChannelHandlerContext for later use using the handlerAdded event:

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
      this.ctx = ctx;
    }

The WebSocketServerProtocolHandler might be a good example to look for dynamically altering the pipeline.

Upvotes: 1

Related Questions