Interface SocketConnection
- All Superinterfaces:
AutoCloseable,Closeable
- All Known Subinterfaces:
TLSConnection
- All Known Implementing Classes:
AbstractSocketConnection,ChannelConnection,NioPlaintextConnection,NioTLSConnection
SocketConnections are usually managed by another class in this library, either an implementation representing a server or a client. These classes are responsible for
calling the callbacks set in this object.
The callbacks registered by applications are named events. The applications registers event handler callbacks using on(String, GenericRunnable). A list of valid event names
for this SocketConnection is listed in the documentation of this method.
None of the methods in this interface throw any checked exceptions. Exceptions in most callbacks or IO operations are caught internally by the implementation and passed to the
error event handlers, which is one of the few callbacks that should not throw an exception itself. After an error, the connection is forcibly closed.
Implementations should inherit from AbstractSocketConnection, because it already contains several implemented methods and utility methods.
- API Note:
- Before version 2.1.0, this interface was an abstract class, which has been partially moved to
AbstractSocketConnection. Note that the specified behavior of some methods has been changed
-
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Closes this connection after all remaining data has been flushed to the socket, which may not be immediately.voidconnect(int timeout) Connects thisSocketConnectionto the previously specified remote address in the constructor.voiddestroy()Similar toclose(), except that the connection is closed immediately, without waiting for data to be flushed to the socket.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.Returns the apparent remote address previously set bysetApparentRemoteAddress(SocketAddress), or the address returned bygetRemoteAddress()if none was set.longReturns the last time any data was sent over this connection, either incoming or outgoing, as returned bySystem.currentTimeMillis().Returns the local address of this connection.Returns the address of the remote host.booleanReturnstrueif theconnectevent has ever executed.default booleanbooleanReturnstrueif this socket is connected.booleanReturnstrueif this socket is writable, meaning data passed towrite(byte[])will not be buffered but written to the socket directly.Removes an event listener previously registered usingon(String, GenericRunnable).Adds an event listener for the given event.default SocketConnectionAdds an event listener for the given event.default SocketConnectionAdds an event listener for the given event.Adds a single-event event listener for the given event.byte[]read()Reads data received from the peer host on this connection.voidsetApparentRemoteAddress(SocketAddress apparentRemoteAddress) Sets a possibly different remote address a client claims to be or act on behalf of.default voidsetOnClose(org.omegazero.common.util.function.ThrowingRunnable onClose) Deprecated.default voidsetOnConnect(org.omegazero.common.util.function.ThrowingRunnable onConnect) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteaddefault voidsetOnData(org.omegazero.common.util.function.ThrowingConsumer<byte[]> onData) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteaddefault voidsetOnError(Consumer<Throwable> onError) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteaddefault voidsetOnTimeout(org.omegazero.common.util.function.ThrowingRunnable onTimeout) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteaddefault voidsetOnWritable(org.omegazero.common.util.function.ThrowingRunnable onWritable) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadvoidsetReadBlock(boolean block) Enables or disables read blocking.default voidwrite(byte[] data) Writes data to this connection for delivery to the peer host.voidwrite(byte[] data, int offset, int length) Writes data to this connection for delivery to the peer host.default voidWrites the given string encoded usingUTF-8to this connection for delivery to the peer host.default 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.
-
Method Details
-
connect
void connect(int timeout) Connects thisSocketConnectionto the previously specified remote address in the constructor. If no address was specified, this method will throw anUnsupportedOperationException.Whether this method is blocking is implementation-defined.
A connection timeout in milliseconds may be specified in the timeout parameter. If the connection has not been established within this timeout, the
timeoutevent is emitted and the connection is closed, and if this method is blocking, it will return. Depending on the implementation and underlying protocol, a timeout may occur earlier or never and may instead cause theerrorevent to be emitted.- Parameters:
timeout- The connection timeout in milliseconds. Disabled if 0
-
read
byte[] read()Reads data received from the peer host on this connection.Whether this method is blocking is implementation-defined. If no data was available,
nullis returned, or the method blocks until data is available.- Returns:
- The read data or
nullif no data is available.
-
write
default 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
void write(byte[] data, int offset, int length) Writes data to this connection for delivery to the peer host.Whether this method is blocking is implementation-defined. A call to this method 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 (see also:writableevent).If this method is called before the
connectevent, 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
default 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
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:
-
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
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.Whether this method is blocking is implementation-defined.
- Returns:
trueif all data could be written to the socket- See Also:
-
close
void close()Closes this connection after all remaining data has been flushed to the socket, which may not be immediately.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
destroy
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. -
getRemoteAddress
SocketAddress getRemoteAddress()Returns the address of the remote host.- Returns:
- The address of the peer host
-
getLocalAddress
SocketAddress getLocalAddress()Returns the local address of this connection.- Returns:
- The local address of this connection
-
getLastIOTime
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
-
isConnected
boolean isConnected()Returnstrueif this socket is connected.- Returns:
trueif this socket is connected
-
hasConnected
boolean hasConnected()Returnstrueif theconnectevent has ever executed. This is alreadytruewhile running the event.- Returns:
trueif theconnectevent has ever been emitted
-
hasDisconnected
default boolean hasDisconnected()- Returns:
trueif this socket has disconnected- Since:
- 1.6
-
isWritable
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
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 emitdataevents 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
SocketAddress getApparentRemoteAddress()Returns the apparent remote address previously set bysetApparentRemoteAddress(SocketAddress), or the address returned bygetRemoteAddress()if none was set.- Returns:
- The apparent remote address
-
on
Adds an event listener for the given event.The following events exist:
connect(): Called when this socket is connected and ready to receive or send data.timeout(): Called when the connect operation started usingconnect(int)times out. If no listener is registered for this event, and a timeout occurs, anerrorevent is emitted instead. This event is followed by acloseevent in both cases.data(byte[]): Called when data is received on this connection.writable(): Called when this socket is ready for writing after awrite(byte[])orconnect(int)operation. This event is not emitted if the socket was previously already writable. This event is also not emitted during awrite(byte[])call to allow the event handler to safely call that method without being called again synchronously.close(): Called when this connection closes and can no longer receive or send data.error(Throwable): Called when an error occurs on this connection. This event is usually followed by acloseevent.
An example for registering an event handler for the
dataevent:connection.on("data", (byte[] data) -> { // .... });- Parameters:
event- The event namerunnable- The callback- Returns:
- This
SocketConnection - Since:
- 2.2.0
-
once
Adds a single-event event listener for the given event. Event listeners registered using this method are only called once, the next time the event is emitted, and are then unregistered.- Parameters:
event- The event namerunnable- The callback- Returns:
- This
SocketConnection - Throws:
UnsupportedOperationException- If single-event event listeners are not supported- Since:
- 2.2.0
-
off
Removes an event listener previously registered usingon(String, GenericRunnable).- Parameters:
event- The event namerunnable- The callback to remove- Returns:
- This
SocketConnection - Since:
- 2.2.0
-
on
default SocketConnection on(String event, org.omegazero.common.event.runnable.GenericRunnable.A0 runnable) Adds an event listener for the given event.Alias for
on(String, GenericRunnable), for zero-argument events.- Parameters:
event- The event namerunnable- The callback- Returns:
- This
SocketConnection - Since:
- 2.2.0
-
on
default SocketConnection on(String event, org.omegazero.common.event.runnable.GenericRunnable.A1<?> runnable) Adds an event listener for the given event.Alias for
on(String, GenericRunnable), for single-argument events.- Parameters:
event- The event namerunnable- The callback- Returns:
- This
SocketConnection - Since:
- 2.2.0
-
setOnConnect
@Deprecated default void setOnConnect(org.omegazero.common.util.function.ThrowingRunnable onConnect) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadSets a callback that is called when this socket is connected and ready to receive or send data.- Parameters:
onConnect- The callback
-
setOnTimeout
@Deprecated default void setOnTimeout(org.omegazero.common.util.function.ThrowingRunnable onTimeout) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadSets a callback that is called when the connect operation started usingconnect(int)times out.If this callback is not set, and a timeout occurs,
onErroris called instead. This callback is followed by aonClosecallback in both cases.- Parameters:
onTimeout- The callback
-
setOnData
@Deprecated default void setOnData(org.omegazero.common.util.function.ThrowingConsumer<byte[]> onData) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadSets a callback that is called when data is received on this connection.- Parameters:
onData- The callback
-
setOnWritable
@Deprecated default void setOnWritable(org.omegazero.common.util.function.ThrowingRunnable onWritable) Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadSets 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
Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadSets a callback that is called when this connection closes and can no longer receive or send data.- Parameters:
onClose- The callback
-
setOnError
Deprecated.Since 2.2.0, useon(String, GenericRunnable)insteadSets a callback that is called when an error occurs on this connection.This callback is usually followed by a
onClosecallback.- Parameters:
onError- The callback
-
on(String, GenericRunnable)instead