Interface ChannelHandlerContext

All Superinterfaces:
AttributeMap, ChannelInboundInvoker, ChannelOutboundInvoker
All Known Implementing Classes:
AbstractChannelHandlerContext, CombinedChannelDuplexHandler.DelegatingChannelHandlerContext, DefaultChannelHandlerContext, DefaultChannelPipeline.HeadContext, DefaultChannelPipeline.TailContext

public interface ChannelHandlerContext extends AttributeMap, ChannelInboundInvoker, ChannelOutboundInvoker
Enables a ChannelHandler to interact with its ChannelPipeline and other handlers. Among other things a handler can notify the next ChannelHandler in the ChannelPipeline as well as modify the ChannelPipeline it belongs to dynamically.

Notify

You can notify the closest handler in the same ChannelPipeline by calling one of the various methods provided here. Please refer to ChannelPipeline to understand how an event flows.

Modifying a pipeline

You can get the ChannelPipeline your handler belongs to by calling pipeline(). A non-trivial application could insert, remove, or replace handlers in the pipeline dynamically at runtime.

Retrieving for later use

You can keep the ChannelHandlerContext for later use, such as triggering an event outside the handler methods, even from a different thread.
 public class MyHandler extends ChannelDuplexHandler {

     private ChannelHandlerContext ctx;

     public void beforeAdd(ChannelHandlerContext ctx) {
         this.ctx = ctx;
     }

     public void login(String username, password) {
         ctx.write(new LoginMessage(username, password));
     }
     ...
 }
 

Storing stateful information

attr(AttributeKey) allow you to store and access stateful information that is related with a ChannelHandler / Channel and its context. Please refer to ChannelHandler to learn various recommended ways to manage stateful information.

A handler can have more than one ChannelHandlerContext

Please note that a ChannelHandler instance can be added to more than one ChannelPipeline. It means a single ChannelHandler instance can have more than one ChannelHandlerContext and therefore the single instance can be invoked with different ChannelHandlerContexts if it is added to one or more ChannelPipelines more than once. Also note that a ChannelHandler that is supposed to be added to multiple ChannelPipelines should be marked as ChannelHandler.Sharable.

Additional resources worth reading

Please refer to the ChannelHandler, and ChannelPipeline to find out more about inbound and outbound operations, what fundamental differences they have, how they flow in a pipeline, and how to handle the operation in your application.