-
- All Known Subinterfaces:
WebSocketFrameDecoder,WebSocketFrameEncoder
- All Known Implementing Classes:
AbstractRemoteAddressFilter,AbstractSniHandler,AbstractTrafficShapingHandler,ApplicationProtocolNegotiationHandler,Base64Decoder,Base64Encoder,ByteArrayDecoder,ByteArrayEncoder,ByteToMessageCodec,ByteToMessageDecoder,ChannelHandlerAdapter,ChannelInitializer,ChannelTrafficShapingHandler,ChunkedWriteHandler,CleartextHttp2ServerUpgradeHandler,CombinedChannelDuplexHandler,CompressionHandler,CorsHandler,DatagramDnsQueryDecoder,DatagramDnsQueryEncoder,DatagramDnsResponseDecoder,DatagramDnsResponseEncoder,DatagramPacketDecoder,DatagramPacketEncoder,DecompressionHandler,DelimiterBasedFrameDecoder,DynamicAddressConnectHandler,FixedLengthFrameDecoder,FlowControlHandler,FlushConsolidationHandler,GlobalChannelTrafficShapingHandler,GlobalTrafficShapingHandler,Http2ChannelDuplexHandler,Http2ConnectionHandler,Http2FrameCodec,Http2MultiplexHandler,Http2StreamFrameToHttpObjectCodec,HttpClientCodec,HttpClientUpgradeHandler,HttpContentCompressor,HttpContentDecoder,HttpContentDecompressor,HttpContentEncoder,HttpObjectAggregator,HttpObjectDecoder,HttpObjectEncoder,HttpRequestDecoder,HttpRequestEncoder,HttpResponseDecoder,HttpResponseEncoder,HttpServerCodec,HttpServerExpectContinueHandler,HttpServerKeepAliveHandler,HttpServerUpgradeHandler,HttpToHttp2ConnectionHandler,IdleStateHandler,InboundHttpToHttp2Adapter,IpSubnetFilter,LengthFieldBasedFrameDecoder,LengthFieldPrepender,LineBasedFrameDecoder,LineEncoder,LoggingHandler,MessageAggregator,MessageToByteEncoder,MessageToMessageCodec,MessageToMessageDecoder,MessageToMessageEncoder,OcspClientHandler,OptionalSslHandler,ReadTimeoutHandler,ResolveAddressHandler,RtspDecoder,RtspEncoder,RuleBasedIpFilter,SimpleChannelInboundHandler,SimpleUserEventChannelHandler,SniHandler,SslClientHelloHandler,SslHandler,SslMasterKeyHandler,StringDecoder,StringEncoder,TcpDnsQueryDecoder,TcpDnsQueryEncoder,TcpDnsResponseDecoder,TcpDnsResponseEncoder,UniqueIpFilter,Utf8FrameValidator,WebSocket13FrameDecoder,WebSocket13FrameEncoder,WebSocketClientCompressionHandler,WebSocketClientExtensionHandler,WebSocketClientProtocolHandler,WebSocketExtensionDecoder,WebSocketExtensionEncoder,WebSocketFrameAggregator,WebSocketServerCompressionHandler,WebSocketServerExtensionHandler,WebSocketServerProtocolHandler,WriteTimeoutHandler
public interface ChannelHandlerHandles an I/O event or intercepts an I/O operation, and forwards it to its next handler in itsChannelPipeline.The context object
A
ChannelHandleris provided with aChannelHandlerContextobject. AChannelHandleris supposed to interact with theChannelPipelineit belongs to via a context object. Using the context object, theChannelHandlercan pass events upstream or downstream, modify the pipeline dynamically, or store the information (usingAttributeKeys) which is specific to the handler.State management
AChannelHandleroften needs to store some stateful information. The simplest and recommended approach is to use member variables:public interface Message { // your methods here } public class DataServerHandler extendsBecause the handler instance has a state variable which is dedicated to one connection, you have to create a new handler instance for each new channel to avoid a race condition where a unauthenticated client can get the confidential information:SimpleChannelInboundHandler<Message> { private boolean loggedIn;@Overridepublic void messageReceived(ChannelHandlerContextctx, Message message) { if (message instanceof LoginMessage) { authenticate((LoginMessage) message); loggedIn = true; } else (message instanceof GetDataMessage) { if (loggedIn) { ctx.writeAndFlush(fetchSecret((GetDataMessage) message)); } else { fail(); } } } ... }// Create a new handler instance per channel. // See
ChannelInitializer.initChannel(Channel). public class DataServerInitializer extendsChannelInitializer<Channel> {@Overridepublic void initChannel(Channelchannel) { channel.pipeline().addLast("handler", new DataServerHandler()); } }Using
Although it's recommended to use member variables to store the state of a handler, for some reason you might not want to create many handler instances. In such a case, you can useAttributeKeysAttributeKeys which is provided byChannelHandlerContext:public interface Message { // your methods here } public class DataServerHandler extendsNow that the state of the handler is attached to theSimpleChannelInboundHandler<Message> { private finalAttributeKey<Boolean> auth =AttributeKey.valueOf("auth");@Overridepublic boolean isSharable() { return true; }@Overridepublic void channelRead(ChannelHandlerContextctx, Message message) {Attribute<Boolean> attr = ctx.attr(auth); if (message instanceof LoginMessage) { authenticate((LoginMessage) o); attr.set(true); } else (message instanceof GetDataMessage) { if (Boolean.TRUE.equals(attr.get())) { ctx.writeAndFlush(fetchSecret((GetDataMessage) o)); } else { fail(); } } } ... }ChannelHandlerContext, you can add the same handler instance to different pipelines:public class DataServerInitializer extends
ChannelInitializer<Channel> { private static final DataServerHandler SHARED = new DataServerHandler();@Overridepublic void initChannel(Channelchannel) { channel.pipeline().addLast("handler", SHARED); } }The
isSharable()methodIn the example above which used an
AttributeKey, you might have noticed theisSharable()method is override to returntrue.If the
isSharable()is returningtrue, it means you can create an instance of the handler just once and add it to one or moreChannelPipelines multiple times without a race condition.If this method is not implemented and return
false, you have to create a new handler instance every time you add it to a pipeline because it has unshared state such as member variables.Additional resources worth reading
Please refer to the
ChannelHandler, andChannelPipelineto 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.
-
-
Method Summary
All Methods Instance Methods Default Methods Modifier and Type Method Description default Future<Void>bind(ChannelHandlerContext ctx, SocketAddress localAddress)Called once a bind operation is made.default voidchannelActive(ChannelHandlerContext ctx)TheChannelof theChannelHandlerContextis now activedefault voidchannelExceptionCaught(ChannelHandlerContext ctx, Throwable cause)Gets called if aThrowablewas thrown when handling inbound events.default voidchannelInactive(ChannelHandlerContext ctx)TheChannelof theChannelHandlerContextwas registered is now inactive and reached its end of lifetime.default voidchannelInboundEvent(ChannelHandlerContext ctx, Object evt)Gets called if a custom inbound event happened.default voidchannelRead(ChannelHandlerContext ctx, Object msg)Invoked when the currentChannelhas read a message from the peer.default voidchannelReadComplete(ChannelHandlerContext ctx)Invoked when the last message read by the current read operation has been consumed bychannelRead(ChannelHandlerContext, Object).default voidchannelRegistered(ChannelHandlerContext ctx)default voidchannelShutdown(ChannelHandlerContext ctx, ChannelShutdownDirection direction)TheChannelof theChannelHandlerContextwas shutdown in one direction.default voidchannelUnregistered(ChannelHandlerContext ctx)default voidchannelWritabilityChanged(ChannelHandlerContext ctx)Gets called once the writable state of aChannelchanged.default Future<Void>close(ChannelHandlerContext ctx)Called once a close operation is made.default Future<Void>connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress)Called once a connect operation is made.default Future<Void>deregister(ChannelHandlerContext ctx)Called once a deregister operation is made from the current registeredEventLoop.default Future<Void>disconnect(ChannelHandlerContext ctx)Called once a disconnect operation is made.default voidflush(ChannelHandlerContext ctx)Called once a flush operation is made.default voidhandlerAdded(ChannelHandlerContext ctx)Gets called after theChannelHandlerwas added to the actual context and it's ready to handle events.default voidhandlerRemoved(ChannelHandlerContext ctx)Gets called after theChannelHandlerwas removed from the actual context and it doesn't handle events anymore.default booleanisSharable()Returnstrueif this handler is sharable and thus can be added to more than oneChannelPipeline.default longpendingOutboundBytes(ChannelHandlerContext ctx)The number of the outbound bytes that are buffered / queued in thisChannelHandler.default voidread(ChannelHandlerContext ctx)InterceptsChannelHandlerContext.read().default Future<Void>register(ChannelHandlerContext ctx)Called once a register operation is made to register for IO on theEventLoop.default Future<Void>sendOutboundEvent(ChannelHandlerContext ctx, Object event)Called once a custom defined outbound event was sent.default Future<Void>shutdown(ChannelHandlerContext ctx, ChannelShutdownDirection direction)Called once a shutdown operation was requested and should be executed.default Future<Void>write(ChannelHandlerContext ctx, Object msg)Called once a write operation is made.
-
-
-
Method Detail
-
handlerAdded
default void handlerAdded(ChannelHandlerContext ctx) throws Exception
Gets called after theChannelHandlerwas added to the actual context and it's ready to handle events.- Throws:
Exception
-
handlerRemoved
default void handlerRemoved(ChannelHandlerContext ctx) throws Exception
Gets called after theChannelHandlerwas removed from the actual context and it doesn't handle events anymore.- Throws:
Exception
-
isSharable
default boolean isSharable()
Returnstrueif this handler is sharable and thus can be added to more than oneChannelPipeline. By default, this method returnsfalse. If this method returnsfalse, you have to create a new handler instance every time you add it to a pipeline because it has unshared state such as member variables.
-
channelRegistered
default void channelRegistered(ChannelHandlerContext ctx) throws Exception
- Throws:
Exception
-
channelUnregistered
default void channelUnregistered(ChannelHandlerContext ctx) throws Exception
- Throws:
Exception
-
channelActive
default void channelActive(ChannelHandlerContext ctx) throws Exception
TheChannelof theChannelHandlerContextis now active- Throws:
Exception
-
channelInactive
default void channelInactive(ChannelHandlerContext ctx) throws Exception
TheChannelof theChannelHandlerContextwas registered is now inactive and reached its end of lifetime.- Throws:
Exception
-
channelShutdown
default void channelShutdown(ChannelHandlerContext ctx, ChannelShutdownDirection direction) throws Exception
TheChannelof theChannelHandlerContextwas shutdown in one direction. This might either be because the remote peer did cause a shutdown of one direction or the shutdown was requested explicit by us and was executed.- Parameters:
ctx- theChannelHandlerContextfor which we notify about the completed shutdown.direction- theChannelShutdownDirectionof the completed shutdown.- Throws:
Exception
-
channelRead
default void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
Invoked when the currentChannelhas read a message from the peer.- Throws:
Exception
-
channelReadComplete
default void channelReadComplete(ChannelHandlerContext ctx) throws Exception
Invoked when the last message read by the current read operation has been consumed bychannelRead(ChannelHandlerContext, Object). IfChannelOption.AUTO_READis off, no further attempt to read an inbound data from the currentChannelwill be made untilChannelHandlerContext.read()is called.- Throws:
Exception
-
channelInboundEvent
default void channelInboundEvent(ChannelHandlerContext ctx, Object evt) throws Exception
Gets called if a custom inbound event happened.- Throws:
Exception
-
channelWritabilityChanged
default void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception
Gets called once the writable state of aChannelchanged. You can check the state withChannel.writableBytes()orChannel.isWritable().- Throws:
Exception
-
channelExceptionCaught
default void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
Gets called if aThrowablewas thrown when handling inbound events.- Throws:
Exception
-
bind
default Future<Void> bind(ChannelHandlerContext ctx, SocketAddress localAddress)
Called once a bind operation is made.- Parameters:
ctx- theChannelHandlerContextfor which the bind operation is madelocalAddress- theSocketAddressto which it should bound- Returns:
- the
Futurewhich will be notified once the operation completes.
-
connect
default Future<Void> connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress)
Called once a connect operation is made.- Parameters:
ctx- theChannelHandlerContextfor which the connect operation is maderemoteAddress- theSocketAddressto which it should connectlocalAddress- theSocketAddresswhich is used as source on connect- Returns:
- the
Futurewhich will be notified once the operation completes.
-
disconnect
default Future<Void> disconnect(ChannelHandlerContext ctx)
Called once a disconnect operation is made.- Parameters:
ctx- theChannelHandlerContextfor which the disconnect operation is made- Returns:
- the
Futurewhich will be notified once the operation completes.
-
close
default Future<Void> close(ChannelHandlerContext ctx)
Called once a close operation is made.- Parameters:
ctx- theChannelHandlerContextfor which the close operation is made- Returns:
- the
Futurewhich will be notified once the operation completes.
-
shutdown
default Future<Void> shutdown(ChannelHandlerContext ctx, ChannelShutdownDirection direction)
Called once a shutdown operation was requested and should be executed.- Parameters:
ctx- theChannelHandlerContextfor which the shutdown operation is madedirection- theChannelShutdownDirectionthat is used.- Returns:
- the
Futurewhich will be notified once the operation completes.
-
register
default Future<Void> register(ChannelHandlerContext ctx)
Called once a register operation is made to register for IO on theEventLoop.- Parameters:
ctx- theChannelHandlerContextfor which the register operation is made- Returns:
- the
Futurewhich will be notified once the operation completes.
-
deregister
default Future<Void> deregister(ChannelHandlerContext ctx)
Called once a deregister operation is made from the current registeredEventLoop.- Parameters:
ctx- theChannelHandlerContextfor which the deregister operation is made- Returns:
- the
Futurewhich will be notified once the operation completes.
-
read
default void read(ChannelHandlerContext ctx)
InterceptsChannelHandlerContext.read().
-
write
default Future<Void> write(ChannelHandlerContext ctx, Object msg)
Called once a write operation is made. The write operation will write the messages through theChannelPipeline. Those are then ready to be flushed to the actualChannelonceChannel.flush()is called.- Parameters:
ctx- theChannelHandlerContextfor which the write operation is mademsg- the message to write- Returns:
- the
Futurewhich will be notified once the operation completes.
-
flush
default void flush(ChannelHandlerContext ctx)
Called once a flush operation is made. The flush operation will try to flush out all previous written messages that are pending.- Parameters:
ctx- theChannelHandlerContextfor which the flush operation is made
-
sendOutboundEvent
default Future<Void> sendOutboundEvent(ChannelHandlerContext ctx, Object event)
Called once a custom defined outbound event was sent. This operation will pass the event through theChannelPipelinein the outbound direction.- Parameters:
ctx- theChannelHandlerContextfor which the operation is made.event- the event.- Returns:
- the
Futurewhich will be notified once the operation completes.
-
pendingOutboundBytes
default long pendingOutboundBytes(ChannelHandlerContext ctx)
The number of the outbound bytes that are buffered / queued in thisChannelHandler. This number will affect the writability of theChanneltogether the buffered / queued bytes in theChannelitself. By default this methods returns0. If theChannelHandlerimplementation buffers / queues outbound data this methods should be implemented to return the correct value.- Parameters:
ctx- theChannelHandlerContextfor which the operation is made.- Returns:
- the number of buffered / queued bytes.
-
-