Module io.netty5.transport
Package io.netty5.channel
Class AbstractChannel<P extends Channel,L extends SocketAddress,R extends SocketAddress>
- java.lang.Object
-
- io.netty5.util.DefaultAttributeMap
-
- io.netty5.channel.AbstractChannel<P,L,R>
-
- All Implemented Interfaces:
Channel,ChannelOutboundInvoker,IoHandle,io.netty5.util.AttributeMap,io.netty5.util.concurrent.FuturePromiseFactory,Comparable<Channel>
- Direct Known Subclasses:
AbstractNioChannel,AbstractServerChannel,EmbeddedChannel,LocalChannel
public abstract class AbstractChannel<P extends Channel,L extends SocketAddress,R extends SocketAddress> extends io.netty5.util.DefaultAttributeMap implements Channel
A skeletalChannelimplementation.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static classAbstractChannel.DefaultAbstractChannelPipelineprotected classAbstractChannel.ReadSinkSink that will be used by#doReadNow(ReadSink)implementations to perform the actual read from the underlying transport (for example a socket).protected classAbstractChannel.WriteSinkSink that will be used by#doWriteNow(WriteSink)implementations.
-
Constructor Summary
Constructors Modifier Constructor Description protectedAbstractChannel(P parent, EventLoop eventLoop, boolean supportingDisconnect)Creates a new instance.protectedAbstractChannel(P parent, EventLoop eventLoop, boolean supportingDisconnect, ReadHandleFactory defaultReadHandleFactory, WriteHandleFactory defaultWriteHandleFactory)Creates a new instance.protectedAbstractChannel(P parent, EventLoop eventLoop, boolean supportingDisconnect, ReadHandleFactory defaultReadHandleFactory, WriteHandleFactory defaultWriteHandleFactory, ChannelId id)Creates a new instance.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description io.netty5.buffer.BufferAllocatorbufferAllocator()Return the assignedBufferAllocatorwhich will be used to allocateBuffers.protected voidcacheAddresses(L localAddress, R remoteAddress)io.netty5.util.concurrent.Future<Void>closeFuture()Returns theFuturewhich will be notified when this channel is closed.protected voidcloseTransport(io.netty5.util.concurrent.Promise<Void> promise)intcompareTo(Channel o)protected abstract voiddoBind(SocketAddress localAddress)Bind theChannelto theSocketAddressprotected voiddoClearScheduledRead()Clear any previous scheduled read.protected abstract voiddoClose()Close theChannelprotected abstract booleandoConnect(SocketAddress remoteAddress, SocketAddress localAddress, io.netty5.buffer.Buffer initialData)Connect to remote peer.protected abstract voiddoDisconnect()Disconnect thisChannelfrom its remote peerprotected abstract booleandoFinishConnect(R requestedRemoteAddress)Finish a connect request.protected abstract voiddoRead(boolean wasReadPendingAlready)Schedule a read operation.protected abstract booleandoReadNow(AbstractChannel.ReadSink readSink)Try to read a message from the transport and dispatch it viaAbstractChannel.ReadSink.processRead(int, int, Object).protected abstract voiddoShutdown(ChannelShutdownDirection direction)Shutdown one direction of theChannel.protected abstract voiddoWriteNow(AbstractChannel.WriteSink writeSink)Called in a loop when writes should be performed until this method returnsfalseor there are no more messages to write.booleanequals(Object o)Returnstrueif and only if the specified object is identical with this channel (i.e:this == o).EventLoopexecutor()protected ObjectfilterOutboundMessage(Object msg)Invoked when a new message is added to to the outbound queue of thisAbstractChannel, so that theChannelimplementation converts the message to another.protected booleanfinishConnect()Should be called once the connect request is ready to be completed andisConnectPending()istrue.protected <T> TgetExtendedOption(ChannelOption<T> option)Override to add support for moreChannelOptions.<T> TgetOption(ChannelOption<T> option)Return the value of the givenChannelOptioninthashCode()Returns the ID of this channel.ChannelIdid()Returns the globally unique identifier of thisChannel.protected booleanisConnectPending()Returns if a connect operation was issued before, andfinishConnect()must be called once the connect operation can be finished.protected booleanisExtendedOptionSupported(ChannelOption<?> option)Override to add support for moreChannelOptions.booleanisOptionSupported(ChannelOption<?> option)protected booleanisReadPending()Returnstrueif a read is currently scheduled and pending for later execution.booleanisRegistered()Return true if registered already.protected booleanisSupportingDisconnect()Returnstrueif the implementation supports disconnecting and re-connecting,falseotherwise.protected booleanisWriteFlushedScheduled()Returnstrueif flushed messages should not be tried to write when callingChannel.flush().LlocalAddress()Returns the local address where this channel is bound to.protected abstract LlocalAddress0()Returns theSocketAddresswhich is bound locally.protected ChannelPipelinenewChannelPipeline()Returns a newChannelPipelineinstance.protected static Set<ChannelOption<?>>newSupportedIdentityOptionsSet(ChannelOption<?>... options)Creates a newSetthat holds the givenChannelOptions.Pparent()Returns the parent of this channel.ChannelPipelinepipeline()Return the assignedChannelPipeline.protected io.netty5.util.concurrent.Future<Executor>prepareToClose()Prepares to close theChannel.protected io.netty5.buffer.BufferAllocatorreadBufferAllocator()Return theBufferAllocatorthat is used to allocateBufferthat are used for reading.protected ReadHandleFactory.ReadHandlereadHandle()protected voidreadIfIsAutoRead()protected voidreadLoopComplete()Called once the read loop completed for this Channel.protected voidreadNow()Reading from the underlying transport now until there is nothing more to read or theReadHandleFactory.ReadHandleis telling us to stop.RremoteAddress()Returns the remote address where this channel is connected to.protected abstract RremoteAddress0()Return theSocketAddresswhich theChannelis connected to.protected <T> voidsetExtendedOption(ChannelOption<T> option, T value)Override to add support for moreChannelOptions.<T> ChannelsetOption(ChannelOption<T> option, T value)Sets a configuration property with the specified name and value.protected voidshutdownReadSide()Shutdown the read side of this channel.StringtoString()Returns theStringrepresentation of this channel.protected static <T extends EventLoopGroup>
TvalidateEventLoopGroup(T group, String name, Class<? extends Channel> channelType)Validate that theEventLoopGroupsupports the givenchannel type.protected static voidvalidateFileRegion(DefaultFileRegion region, long position)Validate aDefaultFileRegionlongwritableBytes()Returns how many bytes can be written before theChannelbecomes 'unwritable'.protected voidwriteFlushed()Writing previous flushed messages ifisWriteFlushedScheduled()returnsfalse, otherwise do nothing.protected voidwriteFlushedNow()Writing previous flushed messages now.protected WriteHandleFactory.WriteHandlewriteHandle()protected voidwriteLoopComplete(boolean allWritten)Called once the write loop completed.-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface io.netty5.channel.Channel
bind, close, connect, connect, deregister, disconnect, flush, isActive, isOpen, isShutdown, isWritable, read, read, register, sendOutboundEvent, shutdown, write, writeAndFlush
-
Methods inherited from interface io.netty5.channel.ChannelOutboundInvoker
newFailedFuture, newPromise, newSucceededFuture, newSucceededFuture
-
-
-
-
Constructor Detail
-
AbstractChannel
protected AbstractChannel(P parent, EventLoop eventLoop, boolean supportingDisconnect)
Creates a new instance.- Parameters:
parent- the parent of this channel.nullif there's no parent.eventLoop- theEventLoopwhich will be used.supportingDisconnect-trueif and only if the channel has thedisconnect()operation that allows a user to disconnect and then call {
-
AbstractChannel
protected AbstractChannel(P parent, EventLoop eventLoop, boolean supportingDisconnect, ReadHandleFactory defaultReadHandleFactory, WriteHandleFactory defaultWriteHandleFactory)
Creates a new instance.- Parameters:
parent- the parent of this channel.nullif there's no parent.eventLoop- theEventLoopwhich will be used.supportingDisconnect-trueif and only if the channel has thedisconnect()operation that allows a user to disconnect and then call {
-
AbstractChannel
protected AbstractChannel(P parent, EventLoop eventLoop, boolean supportingDisconnect, ReadHandleFactory defaultReadHandleFactory, WriteHandleFactory defaultWriteHandleFactory, ChannelId id)
Creates a new instance.- Parameters:
parent- the parent of this channel.nullif there's no parent.eventLoop- theEventLoopwhich will be used.supportingDisconnect-trueif and only if the channel has thedisconnect()operation that allows a user to disconnect and then call {
-
-
Method Detail
-
validateEventLoopGroup
protected static <T extends EventLoopGroup> T validateEventLoopGroup(T group, String name, Class<? extends Channel> channelType)
Validate that theEventLoopGroupsupports the givenchannel type. If validation fails this will throw a runtime exception.- Type Parameters:
T- the concreate type of theEventLoopGroup.- Parameters:
group- the group to check againstname- the name of the param that is used when throwing an exception.channelType- theChanneltype.- Returns:
- the group itself
-
id
public final ChannelId id()
Description copied from interface:ChannelReturns the globally unique identifier of thisChannel.
-
newChannelPipeline
protected ChannelPipeline newChannelPipeline()
Returns a newChannelPipelineinstance.
-
bufferAllocator
public final io.netty5.buffer.BufferAllocator bufferAllocator()
Description copied from interface:ChannelReturn the assignedBufferAllocatorwhich will be used to allocateBuffers.- Specified by:
bufferAllocatorin interfaceChannel
-
parent
public final P parent()
Description copied from interface:ChannelReturns the parent of this channel.
-
pipeline
public final ChannelPipeline pipeline()
Description copied from interface:ChannelReturn the assignedChannelPipeline.
-
executor
public final EventLoop executor()
Description copied from interface:Channel- Specified by:
executorin interfaceChannel- Specified by:
executorin interfaceChannelOutboundInvoker- Returns:
- the executor.
-
localAddress
public final L localAddress()
Description copied from interface:ChannelReturns the local address where this channel is bound to. The returnedSocketAddressis supposed to be down-cast into more concrete type such asInetSocketAddressto retrieve the detailed information.- Specified by:
localAddressin interfaceChannel- Returns:
- the local address of this channel.
nullif this channel is not bound.
-
remoteAddress
public final R remoteAddress()
Description copied from interface:ChannelReturns the remote address where this channel is connected to. The returnedSocketAddressis supposed to be down-cast into more concrete type such asInetSocketAddressto retrieve the detailed information.- Specified by:
remoteAddressin interfaceChannel- Returns:
- the remote address of this channel.
nullif this channel is not connected. If this channel is not connected but it can receive messages from arbitrary remote addresses (e.g.DatagramChannel, useDefaultAddressedEnvelope.recipient()to determine the origination of the received message as this method will returnnull.
-
isRegistered
public final boolean isRegistered()
Description copied from interface:IoHandleReturn true if registered already.- Specified by:
isRegisteredin interfaceIoHandle- Returns:
trueif registered,falseotherwise
-
closeFuture
public final io.netty5.util.concurrent.Future<Void> closeFuture()
Description copied from interface:ChannelReturns theFuturewhich will be notified when this channel is closed. This method always returns the same future instance.- Specified by:
closeFuturein interfaceChannel
-
writableBytes
public final long writableBytes()
Description copied from interface:ChannelReturns how many bytes can be written before theChannelbecomes 'unwritable'. Once aChannelbecomes unwritable, all messages will be queued until the I/O thread is ready to process the queued write requests.- Specified by:
writableBytesin interfaceChannel- Returns:
- the number of bytes that can be written before the
Channelbecomes unwritable.
-
hashCode
public final int hashCode()
Returns the ID of this channel.
-
equals
public final boolean equals(Object o)
Returnstrueif and only if the specified object is identical with this channel (i.e:this == o).
-
compareTo
public final int compareTo(Channel o)
- Specified by:
compareToin interfaceComparable<P extends Channel>
-
toString
public String toString()
Returns theStringrepresentation of this channel. The returned string contains the ID, local address, and remote address of this channel for easier identification.
-
readIfIsAutoRead
protected final void readIfIsAutoRead()
-
readHandle
protected final ReadHandleFactory.ReadHandle readHandle()
-
writeHandle
protected final WriteHandleFactory.WriteHandle writeHandle()
-
closeTransport
protected void closeTransport(io.netty5.util.concurrent.Promise<Void> promise)
-
readNow
protected final void readNow()
Reading from the underlying transport now until there is nothing more to read or theReadHandleFactory.ReadHandleis telling us to stop.
-
shutdownReadSide
protected final void shutdownReadSide()
Shutdown the read side of this channel. Depending on if half-closure is supported or not this will either just shutdown theinboundor close the channel completely.
-
doClearScheduledRead
protected void doClearScheduledRead()
Clear any previous scheduled read. By default, this method does nothing but implementations might override it to add extra logic.
-
doReadNow
protected abstract boolean doReadNow(AbstractChannel.ReadSink readSink) throws Exception
Try to read a message from the transport and dispatch it viaAbstractChannel.ReadSink.processRead(int, int, Object). This method is called in a loop until there is nothing more messages to read or the channel was shutdown / closed. This method should never be called directly by sub-classes, usereadNow()instead.- Parameters:
readSink- theAbstractChannel.ReadSinkthat should be called with messages that are read from the transport to propagate these.- Returns:
trueif the channel should be shutdown / closed.- Throws:
Exception
-
isReadPending
protected final boolean isReadPending()
Returnstrueif a read is currently scheduled and pending for later execution.- Returns:
- if a read is pending.
-
isWriteFlushedScheduled
protected boolean isWriteFlushedScheduled()
Returnstrueif flushed messages should not be tried to write when callingChannel.flush(). Instead these will be written oncewriteFlushedNow()is called, which is typically done once the underlying transport becomes writable again.- Returns:
trueif write will be done later on by callingwriteFlushedNow(),falseotherwise.
-
writeFlushed
protected final void writeFlushed()
Writing previous flushed messages ifisWriteFlushedScheduled()returnsfalse, otherwise do nothing.
-
writeFlushedNow
protected final void writeFlushedNow()
Writing previous flushed messages now.
-
writeLoopComplete
protected void writeLoopComplete(boolean allWritten)
Called once the write loop completed. Subclasses might override this method for custom logic but should also call super.- Parameters:
allWritten-trueif all messages were written during the write loop,falseotherwise.
-
prepareToClose
protected io.netty5.util.concurrent.Future<Executor> prepareToClose()
-
localAddress0
protected abstract L localAddress0()
Returns theSocketAddresswhich is bound locally.- Returns:
- the local address if any,
nullotherwise.
-
remoteAddress0
protected abstract R remoteAddress0()
Return theSocketAddresswhich theChannelis connected to.- Returns:
- the remote address if any,
nullotherwise.
-
doBind
protected abstract void doBind(SocketAddress localAddress) throws Exception
Bind theChannelto theSocketAddress- Parameters:
localAddress- theSocketAddressto bound to.- Throws:
Exception- when an error happens.
-
doDisconnect
protected abstract void doDisconnect() throws ExceptionDisconnect thisChannelfrom its remote peer- Throws:
Exception- thrown on error.
-
doClose
protected abstract void doClose() throws ExceptionClose theChannel- Throws:
Exception- thrown on error.
-
doShutdown
protected abstract void doShutdown(ChannelShutdownDirection direction) throws Exception
Shutdown one direction of theChannel.- Parameters:
direction- the direction to shut down.- Throws:
Exception- thrown on error.
-
doRead
protected abstract void doRead(boolean wasReadPendingAlready) throws ExceptionSchedule a read operation.- Parameters:
wasReadPendingAlready-trueif a read was already pending whenChannel.read()was called.- Throws:
Exception- thrown on error.
-
doWriteNow
protected abstract void doWriteNow(AbstractChannel.WriteSink writeSink) throws Exception
Called in a loop when writes should be performed until this method returnsfalseor there are no more messages to write. Implementations are responsible for handling partial writes, which for example means that ifBuffers are written partial implementations need to ensure thereaderOffsetis updated accordingly.- Parameters:
writeSink- theAbstractChannel.WriteSinkthat must be completed with the write progress.AbstractChannel.WriteSink.complete(long, long, int, boolean)orAbstractChannel.WriteSink.complete(long, Throwable, boolean)must be called exactly once before this method returns non-exceptional.- Throws:
Exception- if an error happened during writing. This will also terminate the write loop.
-
doConnect
protected abstract boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress, io.netty5.buffer.Buffer initialData) throws Exception
Connect to remote peer. This method should never be directly called.- Parameters:
remoteAddress- the address of the remote peer.localAddress- the local address of this channel.initialData- the initial data that is written during connect (ifChannelOption.TCP_FASTOPEN_CONNECTis supported and configured). If data is written care must be taken to update thereader offset.- Returns:
trueif the connect operation was completed,falseiffinishConnect()will be called later again to try finish connecting.- Throws:
Exception- thrown on error.
-
doFinishConnect
protected abstract boolean doFinishConnect(R requestedRemoteAddress) throws Exception
Finish a connect request. This method should never be directly called, usefinishConnect()instead.- Parameters:
requestedRemoteAddress- the remote address of the peer.- Returns:
trueif the connect operations was completed,falseiffinishConnect()will be called later again to try finishing the connect operation.- Throws:
Exception- thrown on error.
-
isConnectPending
protected final boolean isConnectPending()
Returns if a connect operation was issued before, andfinishConnect()must be called once the connect operation can be finished.- Returns:
trueif there is an outstanding connect request.
-
finishConnect
protected final boolean finishConnect()
Should be called once the connect request is ready to be completed andisConnectPending()istrue. Calling this method if noconnect is pendingwill result in anAlreadyConnectedException.- Returns:
trueif the connect operation completed,falseotherwise.
-
filterOutboundMessage
protected Object filterOutboundMessage(Object msg) throws Exception
Invoked when a new message is added to to the outbound queue of thisAbstractChannel, so that theChannelimplementation converts the message to another. (e.g. heap buffer -> direct buffer)- Parameters:
msg- the message to filter / convert.- Throws:
Exception- thrown on error.
-
validateFileRegion
protected static void validateFileRegion(DefaultFileRegion region, long position) throws IOException
Validate aDefaultFileRegion- Parameters:
region- the region to validate.position- the requested position- Throws:
IOException- thrown if requested position is invalid.
-
isSupportingDisconnect
protected final boolean isSupportingDisconnect()
Returnstrueif the implementation supports disconnecting and re-connecting,falseotherwise.- Returns:
trueif supported.
-
getOption
public final <T> T getOption(ChannelOption<T> option)
Description copied from interface:ChannelReturn the value of the givenChannelOption- Specified by:
getOptionin interfaceChannel- Type Parameters:
T- the type of the value.- Parameters:
option- theChannelOption.- Returns:
- the value for the
ChannelOption
-
getExtendedOption
protected <T> T getExtendedOption(ChannelOption<T> option)
Override to add support for moreChannelOptions. You need to also call {@link super} after handling the extra options.- Type Parameters:
T- the value type.- Parameters:
option- theChannelOption.- Returns:
- the value for the option.
- Throws:
UnsupportedOperationException- if theChannelOptionis not supported.
-
setOption
public final <T> Channel setOption(ChannelOption<T> option, T value)
Description copied from interface:ChannelSets a configuration property with the specified name and value.- Specified by:
setOptionin interfaceChannel- Type Parameters:
T- the type of the value.- Parameters:
option- theChannelOption.value- the value for theChannelOption- Returns:
- itself.
-
setExtendedOption
protected <T> void setExtendedOption(ChannelOption<T> option, T value)
Override to add support for moreChannelOptions. You need to also callsuperafter handling the extra options.- Type Parameters:
T- the value type.- Parameters:
option- theChannelOption.- Throws:
UnsupportedOperationException- if theChannelOptionis not supported.
-
isOptionSupported
public final boolean isOptionSupported(ChannelOption<?> option)
Description copied from interface:ChannelReturnstrueif the givenChannelOptionis supported by thisChannelimplementation. If this methods returnsfalse, calls toChannel.setOption(ChannelOption, Object)andChannel.getOption(ChannelOption)with theChannelOptionwill throw anUnsupportedOperationException.- Specified by:
isOptionSupportedin interfaceChannel- Parameters:
option- the option.- Returns:
- true if supported,
falseotherwise.
-
isExtendedOptionSupported
protected boolean isExtendedOptionSupported(ChannelOption<?> option)
Override to add support for moreChannelOptions. You need to also callsuperafter handling the extra options.- Parameters:
option- theChannelOption.- Returns:
trueif supported,falseotherwise.
-
newSupportedIdentityOptionsSet
protected static Set<ChannelOption<?>> newSupportedIdentityOptionsSet(ChannelOption<?>... options)
Creates a newSetthat holds the givenChannelOptions. Sub-classes might use this method for supporting their ownChannelOptions.- Parameters:
options- the options.- Returns:
- the
Setthat holds all the options.
-
readBufferAllocator
protected io.netty5.buffer.BufferAllocator readBufferAllocator()
Return theBufferAllocatorthat is used to allocateBufferthat are used for reading. By default, this will just returnbufferAllocator(). Sub-classes might override this if some special allocator is needed.- Returns:
- the
BufferAllocatorthat is used to allocateBuffers that are used for reading.
-
readLoopComplete
protected void readLoopComplete()
Called once the read loop completed for this Channel. Sub-classes might override this method but should also call super.
-
-