user3338005
user3338005

Reputation: 1

Customize Pipeline Creation in Netty

I am trying to create a class which owns a Netty client connection, and is able to receive all of the channel events, such as channelActive, exceptionCaught, and channelRead, like it would if it was on the end of the pipeline.

My class can create a client TCP connection by calling something like this:

ChannelFuture cf = bootstrap.connect(address, port);

I'm wondering if what I need to do is to insert my class onto the end of the channel pipeline when the channel is created, but I'm not sure how to do that without missing any events (i.e. initial data from the far end). The channel pipeline gets created based on how the bootstrap was configured, so I don't see how I can arrange to have my class added to the pipeline initially.

I can wait for the connection to be made, then do something like this:

cf.get().pipeline().addLast(this);

but I'm not sure that my class is getting added to the pipeline soon enough in this case. For example, will I still see the channelActive event if I do this?

Upvotes: 0

Views: 823

Answers (2)

Jeremy Umansky
Jeremy Umansky

Reputation: 31

If you add the handler in a channel initializer, it will get all the events.

Upvotes: 0

paziwatts
paziwatts

Reputation: 98

Apologies if you already know the thoughts below but if you didn't then might help (the quotes are from the Manning book Netty in Action which is a great book to understand all things Netty):

  • the class that holds the bootstrap usually has the handler configuration(s) - usually an initializer
  • for a ServerBootstrap, which is for a connection oriented protocol, like something on TCP, a handler and childhandler are available

"the ServerBootstrap bootstraps ServerChannel implementations, which are responsible for creating child Channels...When a new connection is accepted, a new child Channel will be created and the ChannelInitializer will add an instance of our [handler] to the Channel's ChannelPipeline."

  • when you initialise your channelpipelines you setup your order of handlers for logging, decoders/encoders, request/response, including any fancy classes for ssl/chunked-file handling etc
  • the request/response handlers usually contain or use other classes that hold the business logic
  • you can dynamically add/remove handlers from the pipeline (like in upgrading pipeline from HTTP to WebSockets)
  • if you want to pull out a message / put a message in somewhere in the middle of the pipeline Netty can operate on the ChannelHandlerContext rather than the pipeline

There are great examples to follow in:

  • Netty source code has an examples folder
  • NettyInAction on GitHub has examples from book
  • Heiko Rupp's blog has some easy to follow examples

Upvotes: 1

Related Questions