Class SocketConnection
- All Implemented Interfaces:
AutoCloseable
- Direct Known Subclasses:
ChannelConnection
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionabstract voidclose()Closes this connection after all remaining data has been flushed to the socket, which may not be immediately.abstract voidconnect(int timeout) Connects thisSocketConnectionto the previously specified remote address in the constructor.abstract voiddestroy()Similar toclose(), except that the connection is closed immediately, without waiting for data to be flushed to the socket.abstract booleanflush()Attempts to flush any queued data after a call towriteQueue(byte[])or data that could not be written previously because the socket was busy.final SocketAddressReturns the apparent remote address previously set bysetApparentRemoteAddress(SocketAddress), or the address returned bygetRemoteAddress()if none was set.final Objectabstract longReturns the last time any data was sent over this connection, either incoming or outgoing, as returned bySystem.currentTimeMillis().abstract SocketAddressReturns the local address of this connection.Returns the read lock.abstract SocketAddressReturns the address of the remote host.Returns the write lock.final voidCalled by subclasses or classes managing thisSocketConnectionif this connection closed.final voidfinal booleanhandleData(byte[] data) Called by classes managing thisSocketConnectionif data was received usingread().final voidCalled by subclasses or classes managing thisSocketConnectionif an error occurred in a callback.final voidfinal voidCalled by subclasses if this socket is writable.final booleanReturnstrueif the onConnect event has ever executed.booleanabstract booleanReturnstrueif this socket is connected.abstract booleanReturnstrueif this socket is writable, meaning data passed towrite(byte[])will not be buffered but written to the socket directly.protected final voidprotected final voidCalled by implementing classes if this connection was established immediately upon callingconnect(int).protected final voidqueueWrite(byte[] data) Called by implementing classes to queue data for writing before this connection has connected.abstract byte[]read()Reads data received from the peer host on this connection.final voidsetApparentRemoteAddress(SocketAddress apparentRemoteAddress) Sets a possibly different remote address a client claims to be or act on behalf of.final voidsetAttachment(Object attachment) final voidsetOnClose(ThrowingRunnable onClose) Sets a callback that is called when this connection closes and can no longer receive or send data.final voidsetOnConnect(ThrowingRunnable onConnect) Sets a callback that is called when this socket is connected and ready to receive or send data.final voidsetOnData(ThrowingConsumer<byte[]> onData) Sets a callback that is called when data is received on this connection.final voidsetOnError(Consumer<Throwable> onError) Sets a callback that is called when an error occurs on this connection.final voidsetOnLocalClose(Consumer<SocketConnection> onLocalClose) final voidsetOnLocalConnect(Consumer<SocketConnection> onLocalConnect) final voidsetOnTimeout(ThrowingRunnable onTimeout) Sets a callback that is called when the connect operation started usingconnect(int)times out.final voidsetOnWritable(ThrowingRunnable onWritable) Sets a callback that is called when this socket is ready for writing after awrite(byte[])orconnect(int)operation.abstract voidsetReadBlock(boolean block) Enables or disables read blocking.voidwrite(byte[] data) Writes data to this connection for delivery to the peer host.abstract voidwrite(byte[] data, int offset, int length) Writes data to this connection for delivery to the peer host.voidWrites the given string encoded usingUTF-8to this connection for delivery to the peer host.voidwriteQueue(byte[] data) Similar towrite(byte[]), except that no attempt will be made to immediately flush the data to the socket, if supported by the implementation.voidwriteQueue(byte[] data, int offset, int length) Similar towrite(byte[], int, int), except that no attempt will be made to immediately flush the data to the socket, if supported by the implementation.
-
Field Details
-
readLock
Lock for read operations. -
writeLock
Lock for write operations.
-
-
Constructor Details
-
SocketConnection
public SocketConnection()
-
-
Method Details
-
connect
public abstract void connect(int timeout) Connects thisSocketConnectionto the previously specified remote address in the constructor. If no address was specified, this method will throw anUnsupportedOperationException.This function is non-blocking.
A connection timeout in milliseconds may be specified in the timeout parameter. If the connection has not been established within this timeout, the handler set using
#setOnTimeout(Runnable)is called and the connection is closed. Depending on the implementation and underlying protocol, a timeout may occur earlier or never and may instead cause theonErrorcallback to be called.- Parameters:
timeout- The connection timeout in milliseconds. Disabled if 0
-
read
public abstract byte[] read()Reads data received from the peer host on this connection.This function is non-blocking. If no data was available,
nullis returned.- Returns:
- The read data or
nullif no data is available.
-
write
public void write(byte[] data) Writes data to this connection for delivery to the peer host.A call to this method is equivalent to a call to
write(data, 0, data.length);- Parameters:
data- The data to write- See Also:
-
write
public abstract void write(byte[] data, int offset, int length) Writes data to this connection for delivery to the peer host.This function is non-blocking and may store data in a temporary write buffer if the underlying socket is busy. An application should try to respect the value of
isWritable()to reduce memory consumption by such write buffer if a lot of data is being written.If this method is called before the
onConnectevent, the data is queued in a temporary buffer and written out when the socket connects.- Parameters:
data- The data to writeoffset- The start index of the data to write in the data byte arraylength- The total number of bytes to write from the data byte array, starting at offset- Throws:
IllegalArgumentException- If offset is negative or if the end index would exceed the length of the array- Since:
- 1.5
- See Also:
-
writeQueue
public void writeQueue(byte[] data) Similar towrite(byte[]), except that no attempt will be made to immediately flush the data to the socket, if supported by the implementation.A call to this method is equivalent to a call to
writeQueue(data, 0, data.length);- Parameters:
data- The data to write- See Also:
-
writeQueue
public void writeQueue(byte[] data, int offset, int length) Similar towrite(byte[], int, int), except that no attempt will be made to immediately flush the data to the socket, if supported by the implementation.- Parameters:
data- The data to writeoffset- The start index of the data to write in the data byte arraylength- The total number of bytes to write from the data byte array, starting at offset- Throws:
IllegalArgumentException- If offset is negative or if the end index would exceed the length of the array- Since:
- 1.5
- See Also:
- Implementation Note:
- The default behavior is to call
write(byte[], int, int). Subclasses should override this method.
-
write
Writes the given string encoded usingUTF-8to this connection for delivery to the peer host.- Parameters:
string- The string- Since:
- 1.6
- See Also:
-
flush
public abstract boolean flush()Attempts to flush any queued data after a call towriteQueue(byte[])or data that could not be written previously because the socket was busy.- Returns:
trueif all data could be written to the socket- See Also:
-
close
public abstract void close()Closes this connection after all remaining data has been flushed to the socket, which may not be immediately.- Specified by:
closein interfaceAutoCloseable
-
destroy
public abstract void destroy()Similar toclose(), except that the connection is closed immediately, without waiting for data to be flushed to the socket.isConnected()should returnfalseimmediately after calling this method. -
isConnected
public abstract boolean isConnected()Returnstrueif this socket is connected.- Returns:
trueif this socket is connected
-
getRemoteAddress
Returns the address of the remote host.- Returns:
- The address of the peer host
-
getLocalAddress
Returns the local address of this connection.- Returns:
- The local address of this connection
-
getLastIOTime
public abstract long getLastIOTime()Returns the last time any data was sent over this connection, either incoming or outgoing, as returned bySystem.currentTimeMillis().- Returns:
- The last time any data was sent over this connection in milliseconds
-
isWritable
public abstract boolean isWritable()Returnstrueif this socket is writable, meaning data passed towrite(byte[])will not be buffered but written to the socket directly.- Returns:
trueif this socket is writable
-
setReadBlock
public abstract void setReadBlock(boolean block) Enables or disables read blocking. If set totrue, the implementation will attempt to block incoming data from being processed and delay it until this is set tofalseagain. Note that the implementation may still fireonDataevents while this option is set totrue.- Parameters:
block- Whether to attempt to block incoming data
-
setApparentRemoteAddress
Sets a possibly different remote address a client claims to be or act on behalf of.For example, if a connection received by a server was proxied through a proxy, this should be set to the actual client address.
- Parameters:
apparentRemoteAddress- The apparent address of the peer
-
getApparentRemoteAddress
Returns the apparent remote address previously set bysetApparentRemoteAddress(SocketAddress), or the address returned bygetRemoteAddress()if none was set.- Returns:
- The apparent remote address
-
handleConnect
public final void handleConnect() -
handleTimeout
public final void handleTimeout() -
handleData
public final boolean handleData(byte[] data) Called by classes managing thisSocketConnectionif data was received usingread(). This method calls theonDatacallback.- Parameters:
data- The data that was received on this connection- Returns:
falseif noonDatahandler was set- See Also:
-
handleWritable
public final void handleWritable()Called by subclasses if this socket is writable. This method calls theonWritablecallback.- See Also:
-
handleError
Called by subclasses or classes managing thisSocketConnectionif an error occurred in a callback. This method calls theonErrorcallback and forcibly closes this connection.- Parameters:
e- The error- Throws:
UnhandledException- If noonErrorhandler is set- See Also:
-
handleClose
public final void handleClose()Called by subclasses or classes managing thisSocketConnectionif this connection closed. This method calls theonErrorcallback on the first invocation of this method.- See Also:
-
setOnConnect
Sets a callback that is called when this socket is connected and ready to receive or send data.- Parameters:
onConnect- The callback
-
setOnTimeout
Sets a callback that is called when the connect operation started usingconnect(int)times out.- Parameters:
onTimeout- The callback
-
setOnData
Sets a callback that is called when data is received on this connection.- Parameters:
onData- The callback
-
setOnWritable
Sets a callback that is called when this socket is ready for writing after awrite(byte[])orconnect(int)operation. This event is not called if the socket was previously already writable. This event is also not called during awrite(byte[])call to allow the handler to safely call that method without being called again synchronously.- Parameters:
onWritable- The callback
-
setOnClose
Sets a callback that is called when this connection closes and can no longer receive or send data.- Parameters:
onClose- The callback
-
setOnError
Sets a callback that is called when an error occurs on this connection.This callback is usually followed by a
onClose(set usingSocketConnection#setOnClose(Runnable)) callback.- Parameters:
onError- The callback
-
setOnLocalClose
-
setOnLocalConnect
-
hasConnected
public final boolean hasConnected()Returnstrueif the onConnect event has ever executed. This is alreadytruewhile running the event.- Returns:
trueif the onConnect event has ever fired
-
hasDisconnected
public boolean hasDisconnected()- Returns:
trueif this socket has disconnected- Since:
- 1.6
-
localConnect
protected final void localConnect()Called by implementing classes if this connection was established immediately upon callingconnect(int). May be used internally by the connection manager. -
localClose
protected final void localClose() -
queueWrite
protected final void queueWrite(byte[] data) Called by implementing classes to queue data for writing before this connection has connected.- Parameters:
data- The data
-
getAttachment
-
setAttachment
-
getReadLock
Returns the read lock. This object is locked every time a read operation that changes the internal state of the connection is performed.- Returns:
- The read lock
- Since:
- 1.4
-
getWriteLock
Returns the write lock. This object is locked every time a write operation that changes the internal state of the connection is performed.- Returns:
- The write lock
- Since:
- 1.4
-