Class SocketWrapperBase<E>
- java.lang.Object
-
- org.apache.tomcat.util.net.SocketWrapperBase<E>
-
- Type Parameters:
E- the socket type
- Direct Known Subclasses:
Nio2Endpoint.Nio2SocketWrapper,NioEndpoint.NioSocketWrapper
public abstract class SocketWrapperBase<E> extends java.lang.ObjectBase class for wrapping a socket connection.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classSocketWrapperBase.BlockingModeDefines the blocking behavior for I/O operations.static interfaceSocketWrapperBase.CompletionCheckInterface for determining whether a completion handler should be invoked.static classSocketWrapperBase.CompletionHandlerCallDefines the possible outcomes for completion handler invocation.static classSocketWrapperBase.CompletionStateRepresents the completion state of an asynchronous I/O operation.protected classSocketWrapperBase.OperationState<A>Internal state tracker for vectored operations.protected classSocketWrapperBase.VectoredIOCompletionHandler<A>Completion handler for vectored operations.
-
Field Summary
Fields Modifier and Type Field Description protected intbufferedWriteSizeThe max size of the individual buffered write buffersprotected java.util.concurrent.atomic.AtomicBooleanclosedIndicates whether the socket has been closed.static SocketWrapperBase.CompletionCheckCOMPLETE_READThis utility CompletionCheck will cause the completion handler to be called once the given buffers are full.static SocketWrapperBase.CompletionCheckCOMPLETE_READ_WITH_COMPLETIONThis utility CompletionCheck will cause the completion handler to be called once the given buffers are full.static SocketWrapperBase.CompletionCheckCOMPLETE_WRITEThis utility CompletionCheck will cause the write to fully write all remaining data.static SocketWrapperBase.CompletionCheckCOMPLETE_WRITE_WITH_COMPLETIONThis utility CompletionCheck will cause the write to fully write all remaining data.protected java.lang.StringlocalAddrLocal address.protected java.lang.StringlocalNameLocal name.protected intlocalPortLocal port.protected WriteBuffernonBlockingWriteBufferAdditional buffer used for non-blocking writes.protected java.io.IOExceptionpreviousIOExceptionThe previous I/O exception that occurred on this socket.static SocketWrapperBase.CompletionCheckREAD_DATAThis utility CompletionCheck will cause the completion handler to be called once some data has been read.protected SocketWrapperBase.OperationState<?>readOperationCurrent read operation state.protected java.util.concurrent.SemaphorereadPendingSemaphore for pending read operations.protected java.lang.StringremoteAddrRemote address.protected java.lang.StringremoteHostRemote host.protected intremotePortRemote port.protected ServletConnectionservletConnectionServlet connection.protected static StringManagersmString manager for this class.protected java.lang.StringsniHostNameSNI host name.protected SocketBufferHandlersocketBufferHandlerThe buffers used for communicating with the socket.protected SocketWrapperBase.OperationState<?>writeOperationCurrent write operation state.protected java.util.concurrent.SemaphorewritePendingSemaphore for pending write operations.
-
Constructor Summary
Constructors Constructor Description SocketWrapperBase(E socket, AbstractEndpoint<E,?> endpoint)Creates a new socket wrapper.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description protected static booleanbuffersArrayHasRemaining(java.nio.ByteBuffer[] buffers, int offset, int length)Checks if any buffer in the specified range has remaining capacity.booleancanWrite()Checks if the socket write buffer is writable and there is no pending non-blocking write data.voidcheckError()Throws the recorded error if one has occurred.voidclose()Close the socket wrapper.abstract SendfileDataBasecreateSendfileData(java.lang.String filename, long pos, long length)Creates a sendfile data object for the specified file.intdecrementKeepAlive()Decrements the number of keep-alive requests remaining.abstract voiddoClientAuth(SSLSupport sslSupport)Require the client to perform CLIENT-CERT authentication if it hasn't already done so.protected abstract voiddoClose()Perform the actual close.protected voiddoWrite(boolean block)Write the contents of the socketWriteBuffer to the socket.protected abstract voiddoWrite(boolean block, java.nio.ByteBuffer from)Write the contents of the ByteBuffer to the socket.voidexecute(java.lang.Runnable runnable)Transfers processing to a container thread.booleanflush(boolean block)Writes as much data as possible from any that remains in the buffers.protected voidflushBlocking()Writes all remaining data from the buffers and blocks until the write is complete.protected abstract booleanflushNonBlocking()Flushes remaining buffered data using a non-blocking write.java.lang.ObjectgetCurrentProcessor()Returns the current processor.protected AbstractEndpoint<E,?>getEndpoint()Returns the endpoint.java.io.IOExceptiongetError()Returns the first I/O error that occurred on this socket.java.lang.StringgetLocalAddr()Returns the local IP address.java.lang.StringgetLocalName()Returns the local host name.intgetLocalPort()Returns the local port number.java.util.concurrent.locks.LockgetLock()Returns the lock for this wrapper.java.lang.StringgetNegotiatedProtocol()Returns the protocol negotiated for this connection.longgetReadTimeout()Returns the read timeout in milliseconds.java.lang.StringgetRemoteAddr()Returns the remote IP address.java.lang.StringgetRemoteHost()Returns the remote host name.intgetRemotePort()Returns the remote port number.ServletConnectiongetServletConnection(java.lang.String protocol, java.lang.String protocolConnectionId)Returns the ServletConnection for this socket, creating it if necessary.java.lang.StringgetSniHostName()Returns the SNI host name.EgetSocket()Returns the wrapped socket.SocketBufferHandlergetSocketBufferHandler()Returns the socket buffer handler.abstract SSLSupportgetSslSupport()Obtain an SSLSupport instance for this socket.longgetWriteTimeout()Returns the write timeout in milliseconds.booleanhasAsyncIO()Allows using NIO2 style read/write.booleanhasDataToRead()Checks if there is data available to read from the socket.booleanhasDataToWrite()Checks if there is data waiting to be written to the socket.booleanhasPerOperationTimeout()Allows indicating if the connector supports per operation timeout.booleanisClosed()Checks if the socket wrapper has been closed.booleanisReadPending()Allows checking if an asynchronous read operation is currently pending.abstract booleanisReadyForRead()Checks if the socket is ready for reading.booleanisReadyForWrite()Checks to see if there are any writes pending and if there are callsregisterWriteInterest()to trigger a callback once the pending writes have completed.booleanisWritePending()Allows checking if an asynchronous write operation is currently pending.booleanneedSemaphores()Allows indicating if the connector needs semaphores.protected abstract <A> SocketWrapperBase.OperationState<A>newOperationState(boolean read, java.nio.ByteBuffer[] buffers, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.util.concurrent.Semaphore semaphore, SocketWrapperBase.VectoredIOCompletionHandler<A> completion)Creates a new operation state for vectored I/O operations.protected abstract voidpopulateLocalAddr()Populates the cached local IP address from the underlying socket.protected abstract voidpopulateLocalName()Populates the cached local host name from the underlying socket.protected abstract voidpopulateLocalPort()Populates the cached local port number from the underlying socket.protected intpopulateReadBuffer(byte[] b, int off, int len)Copies available data from the internal read buffer into the provided byte array.protected intpopulateReadBuffer(java.nio.ByteBuffer to)Copies available data from the internal read buffer into the provided ByteBuffer.protected abstract voidpopulateRemoteAddr()Populates the cached remote IP address from the underlying socket.protected abstract voidpopulateRemoteHost()Populates the cached remote host name from the underlying socket.protected abstract voidpopulateRemotePort()Populates the cached remote port number from the underlying socket.abstract SendfileStateprocessSendfile(SendfileDataBase sendfileData)Starts the sendfile process.voidprocessSocket(SocketEvent socketStatus, boolean dispatch)Processes a socket event.abstract intread(boolean block, byte[] b, int off, int len)Reads data from the socket into a byte array.abstract intread(boolean block, java.nio.ByteBuffer to)Reads data from the socket into a ByteBuffer.<A> SocketWrapperBase.CompletionStateread(long timeout, java.util.concurrent.TimeUnit unit, A attachment, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... dsts)Scatter read.<A> SocketWrapperBase.CompletionStateread(java.nio.ByteBuffer[] dsts, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler)Scatter read.<A> SocketWrapperBase.CompletionStateread(SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... dsts)Scatter read.abstract voidregisterReadInterest()Registers interest in read events.abstract voidregisterWriteInterest()Registers interest in write events.protected voidreset(E closedSocket)Resets the wrapped socket with a new socket instance.abstract voidsetAppReadBufHandler(ApplicationBufferHandler handler)Sets the application-level read buffer handler.voidsetCurrentProcessor(java.lang.Object currentProcessor)Sets the current processor associated with this wrapper.voidsetError(java.io.IOException error)Records the first I/O error that occurs on this socket.voidsetKeepAliveLeft(int keepAliveLeft)Sets the number of keep-alive requests remaining.voidsetNegotiatedProtocol(java.lang.String negotiatedProtocol)Sets the protocol negotiated for this connection.voidsetReadTimeout(long readTimeout)Set the timeout for reading.voidsetSniHostName(java.lang.String sniHostName)Sets the SNI host name.voidsetWriteTimeout(long writeTimeout)Set the timeout for writing.java.lang.ObjecttakeCurrentProcessor()Retrieves and clears the current processor associated with this wrapper.java.lang.StringtoString()Overridden for debug purposes.protected static inttransfer(byte[] from, int offset, int length, java.nio.ByteBuffer to)Transfers data from a byte array into a ByteBuffer.protected static inttransfer(java.nio.ByteBuffer from, java.nio.ByteBuffer to)Transfers data from one ByteBuffer to another.voidunRead(java.nio.ByteBuffer returnedInput)Return input that has been read to the input buffer for re-reading by the correct component.protected <A> SocketWrapperBase.CompletionStatevectoredOperation(boolean read, java.nio.ByteBuffer[] buffers, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler)Vectored operation.voidwrite(boolean block, byte[] buf, int off, int len)Writes the provided data to the socket write buffer.voidwrite(boolean block, java.nio.ByteBuffer from)Writes the provided data to the socket write buffer.<A> SocketWrapperBase.CompletionStatewrite(long timeout, java.util.concurrent.TimeUnit unit, A attachment, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... srcs)Gather write.<A> SocketWrapperBase.CompletionStatewrite(java.nio.ByteBuffer[] srcs, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler)Gather write.<A> SocketWrapperBase.CompletionStatewrite(SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... srcs)Gather write.protected voidwriteBlocking(byte[] buf, int off, int len)Writes the provided data to the socket write buffer.protected voidwriteBlocking(java.nio.ByteBuffer from)Writes the provided data to the socket write buffer.protected voidwriteNonBlocking(byte[] buf, int off, int len)Transfers the data to the socket write buffer (writing that data to the socket if the buffer fills up using a non-blocking write) until either all the data has been transferred and space remains in the socket write buffer or a non-blocking write leaves data in the socket write buffer.protected voidwriteNonBlocking(java.nio.ByteBuffer from)Transfers the data to the socket write buffer (writing that data to the socket if the buffer fills up using a non-blocking write) until either all the data has been transferred and space remains in the socket write buffer or a non-blocking write leaves data in the socket write buffer.protected voidwriteNonBlockingInternal(java.nio.ByteBuffer from)Separate method so it can be re-used by the socket write buffer to write data to the network
-
-
-
Field Detail
-
sm
protected static final StringManager sm
String manager for this class.
-
closed
protected final java.util.concurrent.atomic.AtomicBoolean closed
Indicates whether the socket has been closed.
-
previousIOException
protected volatile java.io.IOException previousIOException
The previous I/O exception that occurred on this socket.
-
localAddr
protected java.lang.String localAddr
Local address.
-
localName
protected java.lang.String localName
Local name.
-
localPort
protected int localPort
Local port.
-
remoteAddr
protected java.lang.String remoteAddr
Remote address.
-
remoteHost
protected java.lang.String remoteHost
Remote host.
-
remotePort
protected int remotePort
Remote port.
-
servletConnection
protected volatile ServletConnection servletConnection
Servlet connection.
-
sniHostName
protected java.lang.String sniHostName
SNI host name.
-
socketBufferHandler
protected volatile SocketBufferHandler socketBufferHandler
The buffers used for communicating with the socket.
-
bufferedWriteSize
protected int bufferedWriteSize
The max size of the individual buffered write buffers
-
nonBlockingWriteBuffer
protected final WriteBuffer nonBlockingWriteBuffer
Additional buffer used for non-blocking writes. Non-blocking writes need to return immediately even if the data cannot be written immediately but the socket buffer may not be big enough to hold all of the unwritten data. This structure provides an additional buffer to hold the data until it can be written. Not that while the Servlet API only allows one non-blocking write at a time, due to buffering and the possible need to write HTTP headers, this layer may see multiple writes.
-
readPending
protected final java.util.concurrent.Semaphore readPending
Semaphore for pending read operations.
-
readOperation
protected volatile SocketWrapperBase.OperationState<?> readOperation
Current read operation state.
-
writePending
protected final java.util.concurrent.Semaphore writePending
Semaphore for pending write operations.
-
writeOperation
protected volatile SocketWrapperBase.OperationState<?> writeOperation
Current write operation state.
-
COMPLETE_WRITE
public static final SocketWrapperBase.CompletionCheck COMPLETE_WRITE
This utility CompletionCheck will cause the write to fully write all remaining data. If the operation completes inline, the completion handler will not be called.
-
COMPLETE_WRITE_WITH_COMPLETION
public static final SocketWrapperBase.CompletionCheck COMPLETE_WRITE_WITH_COMPLETION
This utility CompletionCheck will cause the write to fully write all remaining data. The completion handler will then be called.
-
READ_DATA
public static final SocketWrapperBase.CompletionCheck READ_DATA
This utility CompletionCheck will cause the completion handler to be called once some data has been read. If the operation completes inline, the completion handler will not be called.
-
COMPLETE_READ_WITH_COMPLETION
public static final SocketWrapperBase.CompletionCheck COMPLETE_READ_WITH_COMPLETION
This utility CompletionCheck will cause the completion handler to be called once the given buffers are full. The completion handler will then be called.
-
COMPLETE_READ
public static final SocketWrapperBase.CompletionCheck COMPLETE_READ
This utility CompletionCheck will cause the completion handler to be called once the given buffers are full. If the operation completes inline, the completion handler will not be called.
-
-
Constructor Detail
-
SocketWrapperBase
public SocketWrapperBase(E socket, AbstractEndpoint<E,?> endpoint)
Creates a new socket wrapper.- Parameters:
socket- the socket to wrapendpoint- the endpoint
-
-
Method Detail
-
getSocket
public E getSocket()
Returns the wrapped socket.- Returns:
- the socket
-
reset
protected void reset(E closedSocket)
Resets the wrapped socket with a new socket instance.- Parameters:
closedSocket- the new socket to wrap
-
getEndpoint
protected AbstractEndpoint<E,?> getEndpoint()
Returns the endpoint.- Returns:
- the endpoint
-
getLock
public java.util.concurrent.locks.Lock getLock()
Returns the lock for this wrapper.- Returns:
- the lock
-
getCurrentProcessor
public java.lang.Object getCurrentProcessor()
Returns the current processor.- Returns:
- the current processor
-
setCurrentProcessor
public void setCurrentProcessor(java.lang.Object currentProcessor)
Sets the current processor associated with this wrapper.- Parameters:
currentProcessor- the processor to associate
-
takeCurrentProcessor
public java.lang.Object takeCurrentProcessor()
Retrieves and clears the current processor associated with this wrapper.- Returns:
- the previous processor, or
nullif none was set
-
execute
public void execute(java.lang.Runnable runnable)
Transfers processing to a container thread.- Parameters:
runnable- The actions to process on a container thread- Throws:
java.util.concurrent.RejectedExecutionException- If the runnable cannot be executed
-
getError
public java.io.IOException getError()
Returns the first I/O error that occurred on this socket.- Returns:
- the recorded error, or
nullif no error has occurred
-
setError
public void setError(java.io.IOException error)
Records the first I/O error that occurs on this socket. Subsequent calls are ignored.- Parameters:
error- the error to record
-
checkError
public void checkError() throws java.io.IOExceptionThrows the recorded error if one has occurred.- Throws:
java.io.IOException- if an error was previously recorded
-
getNegotiatedProtocol
public java.lang.String getNegotiatedProtocol()
Returns the protocol negotiated for this connection.- Returns:
- the negotiated protocol, or
nullif none has been negotiated
-
setNegotiatedProtocol
public void setNegotiatedProtocol(java.lang.String negotiatedProtocol)
Sets the protocol negotiated for this connection.- Parameters:
negotiatedProtocol- the negotiated protocol
-
getSniHostName
public java.lang.String getSniHostName()
Returns the SNI host name.- Returns:
- the SNI host name
-
setSniHostName
public void setSniHostName(java.lang.String sniHostName)
Sets the SNI host name.- Parameters:
sniHostName- the SNI host name to set
-
setReadTimeout
public void setReadTimeout(long readTimeout)
Set the timeout for reading. Values of zero or less will be changed to -1.- Parameters:
readTimeout- The timeout in milliseconds. A value of -1 indicates an infinite timeout.
-
getReadTimeout
public long getReadTimeout()
Returns the read timeout in milliseconds.- Returns:
- the read timeout, or -1 for infinite timeout
-
setWriteTimeout
public void setWriteTimeout(long writeTimeout)
Set the timeout for writing. Values of zero or less will be changed to -1.- Parameters:
writeTimeout- The timeout in milliseconds. A value of zero or less indicates an infinite timeout.
-
getWriteTimeout
public long getWriteTimeout()
Returns the write timeout in milliseconds.- Returns:
- the write timeout, or -1 for infinite timeout
-
setKeepAliveLeft
public void setKeepAliveLeft(int keepAliveLeft)
Sets the number of keep-alive requests remaining.- Parameters:
keepAliveLeft- the number of keep-alive requests remaining
-
decrementKeepAlive
public int decrementKeepAlive()
Decrements the number of keep-alive requests remaining.- Returns:
- the updated number of keep-alive requests remaining
-
getRemoteHost
public java.lang.String getRemoteHost()
Returns the remote host name.- Returns:
- the remote host name
-
populateRemoteHost
protected abstract void populateRemoteHost()
Populates the cached remote host name from the underlying socket.
-
getRemoteAddr
public java.lang.String getRemoteAddr()
Returns the remote IP address.- Returns:
- the remote IP address
-
populateRemoteAddr
protected abstract void populateRemoteAddr()
Populates the cached remote IP address from the underlying socket.
-
getRemotePort
public int getRemotePort()
Returns the remote port number.- Returns:
- the remote port number
-
populateRemotePort
protected abstract void populateRemotePort()
Populates the cached remote port number from the underlying socket.
-
getLocalName
public java.lang.String getLocalName()
Returns the local host name.- Returns:
- the local host name
-
populateLocalName
protected abstract void populateLocalName()
Populates the cached local host name from the underlying socket.
-
getLocalAddr
public java.lang.String getLocalAddr()
Returns the local IP address.- Returns:
- the local IP address
-
populateLocalAddr
protected abstract void populateLocalAddr()
Populates the cached local IP address from the underlying socket.
-
getLocalPort
public int getLocalPort()
Returns the local port number.- Returns:
- the local port number
-
populateLocalPort
protected abstract void populateLocalPort()
Populates the cached local port number from the underlying socket.
-
getSocketBufferHandler
public SocketBufferHandler getSocketBufferHandler()
Returns the socket buffer handler.- Returns:
- the socket buffer handler
-
hasDataToRead
public boolean hasDataToRead()
Checks if there is data available to read from the socket.- Returns:
truesince it is always safe to attempt a read
-
hasDataToWrite
public boolean hasDataToWrite()
Checks if there is data waiting to be written to the socket.- Returns:
trueif there is pending write data
-
isReadyForWrite
public boolean isReadyForWrite()
Checks to see if there are any writes pending and if there are callsregisterWriteInterest()to trigger a callback once the pending writes have completed.Note: Once this method has returned
falseit MUST NOT be called again until the pending write has completed and the callback has been fired. TODO: ModifyregisterWriteInterest()so the above restriction is enforced there rather than relying on the caller.- Returns:
trueif no writes are pending and data can be written otherwisefalse
-
canWrite
public boolean canWrite()
Checks if the socket write buffer is writable and there is no pending non-blocking write data.- Returns:
trueif the socket is ready for writing
-
toString
public java.lang.String toString()
Overridden for debug purposes. No guarantees are made about the format of this message which may vary significantly between point releases.- Overrides:
toStringin classjava.lang.Object
-
read
public abstract int read(boolean block, byte[] b, int off, int len) throws java.io.IOExceptionReads data from the socket into a byte array.- Parameters:
block- Whether to blockb- The byte array to read intooff- The offset in the arraylen- The number of bytes to read- Returns:
- the number of bytes read
- Throws:
java.io.IOException- If an I/O error occurs
-
read
public abstract int read(boolean block, java.nio.ByteBuffer to) throws java.io.IOExceptionReads data from the socket into a ByteBuffer.- Parameters:
block- Whether to blockto- The ByteBuffer to read into- Returns:
- the number of bytes read
- Throws:
java.io.IOException- If an I/O error occurs
-
isReadyForRead
public abstract boolean isReadyForRead() throws java.io.IOExceptionChecks if the socket is ready for reading.- Returns:
trueif data is available to read- Throws:
java.io.IOException- If an I/O error occurs
-
setAppReadBufHandler
public abstract void setAppReadBufHandler(ApplicationBufferHandler handler)
Sets the application-level read buffer handler.- Parameters:
handler- The application buffer handler
-
populateReadBuffer
protected int populateReadBuffer(byte[] b, int off, int len)Copies available data from the internal read buffer into the provided byte array.- Parameters:
b- the byte array to populateoff- the offset in the arraylen- the maximum number of bytes to copy- Returns:
- the number of bytes copied
-
populateReadBuffer
protected int populateReadBuffer(java.nio.ByteBuffer to)
Copies available data from the internal read buffer into the provided ByteBuffer.- Parameters:
to- the ByteBuffer to populate- Returns:
- the number of bytes copied
-
unRead
public void unRead(java.nio.ByteBuffer returnedInput)
Return input that has been read to the input buffer for re-reading by the correct component. There are times when a component may read more data than it needs before it passes control to another component. One example of this is during HTTP upgrade. If an (arguably misbehaving client) sends data associated with the upgraded protocol before the HTTP upgrade completes, the HTTP handler may read it. This method provides a way for that data to be returned so it can be processed by the correct component.- Parameters:
returnedInput- The input to return to the input buffer.
-
close
public void close()
Close the socket wrapper.
-
doClose
protected abstract void doClose()
Perform the actual close. The closed atomic boolean guarantees this will be called only once per wrapper.
-
isClosed
public boolean isClosed()
Checks if the socket wrapper has been closed.- Returns:
trueif the wrapper has been closed
-
write
public final void write(boolean block, byte[] buf, int off, int len) throws java.io.IOExceptionWrites the provided data to the socket write buffer. If the socket write buffer fills during the write, the content of the socket write buffer is written to the network and this method starts to fill the socket write buffer again. Depending on the size of the data to write, there may be multiple writes to the network.Non-blocking writes must return immediately and the byte array holding the data to be written must be immediately available for re-use. It may not be possible to write sufficient data to the network to allow this to happen. In this case data that cannot be written to the network and cannot be held by the socket buffer is stored in the non-blocking write buffer.
Note: There is an implementation assumption that, before switching from non-blocking writes to blocking writes, any data remaining in the non-blocking write buffer will have been written to the network.
- Parameters:
block-trueif a blocking write should be used, otherwise a non-blocking write will be usedbuf- The byte array containing the data to be writtenoff- The offset within the byte array of the data to be writtenlen- The length of the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
write
public final void write(boolean block, java.nio.ByteBuffer from) throws java.io.IOExceptionWrites the provided data to the socket write buffer. If the socket write buffer fills during the write, the content of the socket write buffer is written to the network and this method starts to fill the socket write buffer again. Depending on the size of the data to write, there may be multiple writes to the network.Non-blocking writes must return immediately and the ByteBuffer holding the data to be written must be immediately available for re-use. It may not be possible to write sufficient data to the network to allow this to happen. In this case data that cannot be written to the network and cannot be held by the socket buffer is stored in the non-blocking write buffer.
Note: There is an implementation assumption that, before switching from non-blocking writes to blocking writes, any data remaining in the non-blocking write buffer will have been written to the network.
- Parameters:
block-trueif a blocking write should be used, otherwise a non-blocking write will be usedfrom- The ByteBuffer containing the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
writeBlocking
protected void writeBlocking(byte[] buf, int off, int len) throws java.io.IOExceptionWrites the provided data to the socket write buffer. If the socket write buffer fills during the write, the content of the socket write buffer is written to the network using a blocking write. Once that blocking write is complete, this method starts to fill the socket write buffer again. Depending on the size of the data to write, there may be multiple writes to the network. On completion of this method there will always be space remaining in the socket write buffer.- Parameters:
buf- The byte array containing the data to be writtenoff- The offset within the byte array of the data to be writtenlen- The length of the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
writeBlocking
protected void writeBlocking(java.nio.ByteBuffer from) throws java.io.IOExceptionWrites the provided data to the socket write buffer. If the socket write buffer fills during the write, the content of the socket write buffer is written to the network using a blocking write. Once that blocking write is complete, this method starts to fill the socket write buffer again. Depending on the size of the data to write, there may be multiple writes to the network. On completion of this method there will always be space remaining in the socket write buffer.- Parameters:
from- The ByteBuffer containing the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
writeNonBlocking
protected void writeNonBlocking(byte[] buf, int off, int len) throws java.io.IOExceptionTransfers the data to the socket write buffer (writing that data to the socket if the buffer fills up using a non-blocking write) until either all the data has been transferred and space remains in the socket write buffer or a non-blocking write leaves data in the socket write buffer. After an incomplete write, any data remaining to be transferred to the socket write buffer will be copied to the socket write buffer. If the remaining data is too big for the socket write buffer, the socket write buffer will be filled and the additional data written to the non-blocking write buffer.- Parameters:
buf- The byte array containing the data to be writtenoff- The offset within the byte array of the data to be writtenlen- The length of the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
writeNonBlocking
protected void writeNonBlocking(java.nio.ByteBuffer from) throws java.io.IOExceptionTransfers the data to the socket write buffer (writing that data to the socket if the buffer fills up using a non-blocking write) until either all the data has been transferred and space remains in the socket write buffer or a non-blocking write leaves data in the socket write buffer. After an incomplete write, any data remaining to be transferred to the socket write buffer will be copied to the socket write buffer. If the remaining data is too big for the socket write buffer, the socket write buffer will be filled and the additional data written to the non-blocking write buffer.- Parameters:
from- The ByteBuffer containing the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
writeNonBlockingInternal
protected void writeNonBlockingInternal(java.nio.ByteBuffer from) throws java.io.IOExceptionSeparate method so it can be re-used by the socket write buffer to write data to the network- Parameters:
from- The ByteBuffer containing the data to be written- Throws:
java.io.IOException- If an IO error occurs during the write
-
flush
public boolean flush(boolean block) throws java.io.IOExceptionWrites as much data as possible from any that remains in the buffers.- Parameters:
block-trueif a blocking write should be used, otherwise a non-blocking write will be used- Returns:
trueif data remains to be flushed after this method completes, otherwisefalse. In blocking mode therefore, the return value should always befalse- Throws:
java.io.IOException- If an IO error occurs during the write
-
flushBlocking
protected void flushBlocking() throws java.io.IOExceptionWrites all remaining data from the buffers and blocks until the write is complete.- Throws:
java.io.IOException- If an IO error occurs during the write
-
flushNonBlocking
protected abstract boolean flushNonBlocking() throws java.io.IOExceptionFlushes remaining buffered data using a non-blocking write.- Returns:
trueif data remains to be flushed after this method completes, otherwisefalse- Throws:
java.io.IOException- If an IO error occurs during the write
-
doWrite
protected void doWrite(boolean block) throws java.io.IOExceptionWrite the contents of the socketWriteBuffer to the socket. For blocking writes either then entire contents of the buffer will be written or an IOException will be thrown. Partial blocking writes will not occur.- Parameters:
block- Should the write be blocking or not?- Throws:
java.io.IOException- If an I/O error such as a timeout occurs during the write
-
doWrite
protected abstract void doWrite(boolean block, java.nio.ByteBuffer from) throws java.io.IOExceptionWrite the contents of the ByteBuffer to the socket. For blocking writes either then entire contents of the buffer will be written or an IOException will be thrown. Partial blocking writes will not occur.- Parameters:
block- Should the write be blocking or not?from- the ByteBuffer containing the data to be written- Throws:
java.io.IOException- If an I/O error such as a timeout occurs during the write
-
processSocket
public void processSocket(SocketEvent socketStatus, boolean dispatch)
Processes a socket event.- Parameters:
socketStatus- The socket event statusdispatch- Whether to dispatch to a worker thread
-
registerReadInterest
public abstract void registerReadInterest()
Registers interest in read events.
-
registerWriteInterest
public abstract void registerWriteInterest()
Registers interest in write events.
-
createSendfileData
public abstract SendfileDataBase createSendfileData(java.lang.String filename, long pos, long length)
Creates a sendfile data object for the specified file.- Parameters:
filename- The file to sendpos- The starting position in the filelength- The number of bytes to send- Returns:
- a new sendfile data object
-
processSendfile
public abstract SendfileState processSendfile(SendfileDataBase sendfileData)
Starts the sendfile process. It is expected that if the sendfile process does not complete during this call and does not report an error, that the caller will not add the socket to the poller (or equivalent). That is the responsibility of this method.- Parameters:
sendfileData- Data representing the file to send- Returns:
- The state of the sendfile process after the first write.
-
doClientAuth
public abstract void doClientAuth(SSLSupport sslSupport) throws java.io.IOException
Require the client to perform CLIENT-CERT authentication if it hasn't already done so.- Parameters:
sslSupport- The SSL/TLS support instance currently being used by the connection that may need updating after the client authentication- Throws:
java.io.IOException- If authentication is required then there will be I/O with the client and this exception will be thrown if that goes wrong
-
getSslSupport
public abstract SSLSupport getSslSupport()
Obtain an SSLSupport instance for this socket.- Returns:
- An SSLSupport instance for this socket.
-
hasAsyncIO
public boolean hasAsyncIO()
Allows using NIO2 style read/write.- Returns:
trueif the connector has the capability enabled
-
needSemaphores
public boolean needSemaphores()
Allows indicating if the connector needs semaphores.- Returns:
- This default implementation always returns
false
-
hasPerOperationTimeout
public boolean hasPerOperationTimeout()
Allows indicating if the connector supports per operation timeout.- Returns:
- This default implementation always returns
false
-
isReadPending
public boolean isReadPending()
Allows checking if an asynchronous read operation is currently pending.- Returns:
trueif the endpoint supports asynchronous IO and a read operation is being processed asynchronously
-
isWritePending
public boolean isWritePending()
Allows checking if an asynchronous write operation is currently pending.- Returns:
trueif the endpoint supports asynchronous IO and a write operation is being processed asynchronously
-
read
public final <A> SocketWrapperBase.CompletionState read(long timeout, java.util.concurrent.TimeUnit unit, A attachment, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... dsts)
Scatter read. The completion handler will be called once some data has been read or an error occurred. The default NIO2 behavior is used: the completion handler will be called as soon as some data has been read, even if the read has completed inline.- Type Parameters:
A- The attachment type- Parameters:
timeout- timeout duration for the readunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlerhandler- to call when the IO is completedsts- buffers- Returns:
- the completion state (done, done inline, or still pending)
-
read
public final <A> SocketWrapperBase.CompletionState read(SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... dsts)
Scatter read. The completion handler will be called once some data has been read or an error occurred. If a CompletionCheck object has been provided, the completion handler will only be called if the callHandler method returned true. If no CompletionCheck object has been provided, the default NIO2 behavior is used: the completion handler will be called as soon as some data has been read, even if the read has completed inline.- Type Parameters:
A- The attachment type- Parameters:
block- is the blocking mode that will be used for this operationtimeout- timeout duration for the readunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlercheck- for the IO operation completionhandler- to call when the IO is completedsts- buffers- Returns:
- the completion state (done, done inline, or still pending)
-
read
public final <A> SocketWrapperBase.CompletionState read(java.nio.ByteBuffer[] dsts, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler)
Scatter read. The completion handler will be called once some data has been read or an error occurred. If a CompletionCheck object has been provided, the completion handler will only be called if the callHandler method returned true. If no CompletionCheck object has been provided, the default NIO2 behavior is used: the completion handler will be called as soon as some data has been read, even if the read has completed inline.- Type Parameters:
A- The attachment type- Parameters:
dsts- buffersoffset- in the buffer arraylength- in the buffer arrayblock- is the blocking mode that will be used for this operationtimeout- timeout duration for the readunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlercheck- for the IO operation completionhandler- to call when the IO is complete- Returns:
- the completion state (done, done inline, or still pending)
-
write
public final <A> SocketWrapperBase.CompletionState write(long timeout, java.util.concurrent.TimeUnit unit, A attachment, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... srcs)
Gather write. The completion handler will be called once some data has been written or an error occurred. The default NIO2 behavior is used: the completion handler will be called, even if the write is incomplete and data remains in the buffers, or if the write completed inline.- Type Parameters:
A- The attachment type- Parameters:
timeout- timeout duration for the writeunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlerhandler- to call when the IO is completesrcs- buffers- Returns:
- the completion state (done, done inline, or still pending)
-
write
public final <A> SocketWrapperBase.CompletionState write(SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.nio.ByteBuffer... srcs)
Gather write. The completion handler will be called once some data has been written or an error occurred. If a CompletionCheck object has been provided, the completion handler will only be called if the callHandler method returned true. If no CompletionCheck object has been provided, the default NIO2 behavior is used: the completion handler will be called, even if the write is incomplete and data remains in the buffers, or if the write completed inline.- Type Parameters:
A- The attachment type- Parameters:
block- is the blocking mode that will be used for this operationtimeout- timeout duration for the writeunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlercheck- for the IO operation completionhandler- to call when the IO is completesrcs- buffers- Returns:
- the completion state (done, done inline, or still pending)
-
write
public final <A> SocketWrapperBase.CompletionState write(java.nio.ByteBuffer[] srcs, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler)
Gather write. The completion handler will be called once some data has been written or an error occurred. If a CompletionCheck object has been provided, the completion handler will only be called if the callHandler method returned true. If no CompletionCheck object has been provided, the default NIO2 behavior is used: the completion handler will be called, even if the write is incomplete and data remains in the buffers, or if the write completed inline.- Type Parameters:
A- The attachment type- Parameters:
srcs- buffersoffset- in the buffer arraylength- in the buffer arrayblock- is the blocking mode that will be used for this operationtimeout- timeout duration for the writeunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlercheck- for the IO operation completionhandler- to call when the IO is complete- Returns:
- the completion state (done, done inline, or still pending)
-
vectoredOperation
protected final <A> SocketWrapperBase.CompletionState vectoredOperation(boolean read, java.nio.ByteBuffer[] buffers, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler)
Vectored operation. The completion handler will be called once the operation is complete or an error occurred. If a CompletionCheck object has been provided, the completion handler will only be called if the callHandler method returned true. If no CompletionCheck object has been provided, the default NIO2 behavior is used: the completion handler will be called, even if the operation is incomplete, or if the operation completed inline.- Type Parameters:
A- The attachment type- Parameters:
read- true if the operation is a read, false if it is a writebuffers- buffersoffset- in the buffer arraylength- in the buffer arrayblock- is the blocking mode that will be used for this operationtimeout- timeout duration for the writeunit- units for the timeout durationattachment- an object to attach to the I/O operation that will be used when calling the completion handlercheck- for the IO operation completionhandler- to call when the IO is complete- Returns:
- the completion state (done, done inline, or still pending)
-
newOperationState
protected abstract <A> SocketWrapperBase.OperationState<A> newOperationState(boolean read, java.nio.ByteBuffer[] buffers, int offset, int length, SocketWrapperBase.BlockingMode block, long timeout, java.util.concurrent.TimeUnit unit, A attachment, SocketWrapperBase.CompletionCheck check, java.nio.channels.CompletionHandler<java.lang.Long,? super A> handler, java.util.concurrent.Semaphore semaphore, SocketWrapperBase.VectoredIOCompletionHandler<A> completion)
Creates a new operation state for vectored I/O operations.- Type Parameters:
A- The attachment type- Parameters:
read- Whether this is a read operationbuffers- The buffers for the operationoffset- The offset in the buffer arraylength- The number of buffersblock- The blocking modetimeout- The timeout durationunit- The timeout time unitattachment- An attachment objectcheck- The completion checkhandler- The completion handlersemaphore- The semaphore for synchronizationcompletion- The vectored I/O completion handler- Returns:
- a new operation state instance
-
transfer
protected static int transfer(byte[] from, int offset, int length, java.nio.ByteBuffer to)Transfers data from a byte array into a ByteBuffer.- Parameters:
from- the source byte arrayoffset- the offset in the source arraylength- the maximum number of bytes to transferto- the destination ByteBuffer- Returns:
- the number of bytes transferred
-
transfer
protected static int transfer(java.nio.ByteBuffer from, java.nio.ByteBuffer to)Transfers data from one ByteBuffer to another.- Parameters:
from- the source ByteBufferto- the destination ByteBuffer- Returns:
- the number of bytes transferred
-
buffersArrayHasRemaining
protected static boolean buffersArrayHasRemaining(java.nio.ByteBuffer[] buffers, int offset, int length)Checks if any buffer in the specified range has remaining capacity.- Parameters:
buffers- the array of ByteBuffersoffset- the starting index in the arraylength- the number of buffers to check- Returns:
trueif any buffer has remaining capacity
-
getServletConnection
public ServletConnection getServletConnection(java.lang.String protocol, java.lang.String protocolConnectionId)
Returns the ServletConnection for this socket, creating it if necessary.- Parameters:
protocol- the protocol nameprotocolConnectionId- the protocol-level connection ID- Returns:
- the ServletConnection instance
-
-