-
- 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 ChannelHandler
Handles an I/O event or intercepts an I/O operation, and forwards it to its next handler in itsChannelPipeline
.The context object
A
ChannelHandler
is provided with aChannelHandlerContext
object. AChannelHandler
is supposed to interact with theChannelPipeline
it belongs to via a context object. Using the context object, theChannelHandler
can pass events upstream or downstream, modify the pipeline dynamically, or store the information (usingAttributeKey
s) which is specific to the handler.State management
AChannelHandler
often 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 extends
Because 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;@Override
public void messageReceived(ChannelHandlerContext
ctx, 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
> {@Override
public void initChannel(Channel
channel) { 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 useAttributeKey
sAttributeKey
s which is provided byChannelHandlerContext
:public interface Message { // your methods here } public class DataServerHandler extends
Now that the state of the handler is attached to theSimpleChannelInboundHandler
<Message> { private finalAttributeKey
<Boolean
> auth =AttributeKey.valueOf("auth")
;@Override
public boolean isSharable() { return true; }@Override
public void channelRead(ChannelHandlerContext
ctx, 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();@Override
public void initChannel(Channel
channel) { 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 moreChannelPipeline
s 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
, andChannelPipeline
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.
-
-
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 void
channelActive(ChannelHandlerContext ctx)
TheChannel
of theChannelHandlerContext
is now activedefault void
channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause)
Gets called if aThrowable
was thrown when handling inbound events.default void
channelInactive(ChannelHandlerContext ctx)
TheChannel
of theChannelHandlerContext
was registered is now inactive and reached its end of lifetime.default void
channelInboundEvent(ChannelHandlerContext ctx, Object evt)
Gets called if a custom inbound event happened.default void
channelRead(ChannelHandlerContext ctx, Object msg)
Invoked when the currentChannel
has read a message from the peer.default void
channelReadComplete(ChannelHandlerContext ctx)
Invoked when the last message read by the current read operation has been consumed bychannelRead(ChannelHandlerContext, Object)
.default void
channelRegistered(ChannelHandlerContext ctx)
default void
channelShutdown(ChannelHandlerContext ctx, ChannelShutdownDirection direction)
TheChannel
of theChannelHandlerContext
was shutdown in one direction.default void
channelUnregistered(ChannelHandlerContext ctx)
default void
channelWritabilityChanged(ChannelHandlerContext ctx)
Gets called once the writable state of aChannel
changed.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 void
flush(ChannelHandlerContext ctx)
Called once a flush operation is made.default void
handlerAdded(ChannelHandlerContext ctx)
Gets called after theChannelHandler
was added to the actual context and it's ready to handle events.default void
handlerRemoved(ChannelHandlerContext ctx)
Gets called after theChannelHandler
was removed from the actual context and it doesn't handle events anymore.default boolean
isSharable()
Returnstrue
if this handler is sharable and thus can be added to more than oneChannelPipeline
.default long
pendingOutboundBytes(ChannelHandlerContext ctx)
The number of the outbound bytes that are buffered / queued in thisChannelHandler
.default void
read(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 theChannelHandler
was 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 theChannelHandler
was removed from the actual context and it doesn't handle events anymore.- Throws:
Exception
-
isSharable
default boolean isSharable()
Returnstrue
if 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
TheChannel
of theChannelHandlerContext
is now active- Throws:
Exception
-
channelInactive
default void channelInactive(ChannelHandlerContext ctx) throws Exception
TheChannel
of theChannelHandlerContext
was registered is now inactive and reached its end of lifetime.- Throws:
Exception
-
channelShutdown
default void channelShutdown(ChannelHandlerContext ctx, ChannelShutdownDirection direction) throws Exception
TheChannel
of theChannelHandlerContext
was 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
- theChannelHandlerContext
for which we notify about the completed shutdown.direction
- theChannelShutdownDirection
of the completed shutdown.- Throws:
Exception
-
channelRead
default void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
Invoked when the currentChannel
has 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_READ
is off, no further attempt to read an inbound data from the currentChannel
will 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 aChannel
changed. You can check the state withChannel.writableBytes()
orChannel.isWritable()
.- Throws:
Exception
-
channelExceptionCaught
default void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
Gets called if aThrowable
was 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
- theChannelHandlerContext
for which the bind operation is madelocalAddress
- theSocketAddress
to which it should bound- Returns:
- the
Future
which 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
- theChannelHandlerContext
for which the connect operation is maderemoteAddress
- theSocketAddress
to which it should connectlocalAddress
- theSocketAddress
which is used as source on connect- Returns:
- the
Future
which will be notified once the operation completes.
-
disconnect
default Future<Void> disconnect(ChannelHandlerContext ctx)
Called once a disconnect operation is made.- Parameters:
ctx
- theChannelHandlerContext
for which the disconnect operation is made- Returns:
- the
Future
which will be notified once the operation completes.
-
close
default Future<Void> close(ChannelHandlerContext ctx)
Called once a close operation is made.- Parameters:
ctx
- theChannelHandlerContext
for which the close operation is made- Returns:
- the
Future
which 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
- theChannelHandlerContext
for which the shutdown operation is madedirection
- theChannelShutdownDirection
that is used.- Returns:
- the
Future
which 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
- theChannelHandlerContext
for which the register operation is made- Returns:
- the
Future
which 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
- theChannelHandlerContext
for which the deregister operation is made- Returns:
- the
Future
which 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 actualChannel
onceChannel.flush()
is called.- Parameters:
ctx
- theChannelHandlerContext
for which the write operation is mademsg
- the message to write- Returns:
- the
Future
which 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
- theChannelHandlerContext
for 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 theChannelPipeline
in the outbound direction.- Parameters:
ctx
- theChannelHandlerContext
for which the operation is made.event
- the event.- Returns:
- the
Future
which 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 theChannel
together the buffered / queued bytes in theChannel
itself. By default this methods returns0
. If theChannelHandler
implementation buffers / queues outbound data this methods should be implemented to return the correct value.- Parameters:
ctx
- theChannelHandlerContext
for which the operation is made.- Returns:
- the number of buffered / queued bytes.
-
-