Interface SocketConnection
- All Superinterfaces:
AutoCloseable
,Closeable
- All Known Subinterfaces:
TLSConnection
- All Known Implementing Classes:
AbstractSocketConnection
,ChannelConnection
,NioPlaintextConnection
,NioTLSConnection
SocketConnection
s 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 TypeMethodDescriptionvoid
close()
Closes this connection after all remaining data has been flushed to the socket, which may not be immediately.void
connect
(int timeout) Connects thisSocketConnection
to the previously specified remote address in the constructor.void
destroy()
Similar toclose()
, except that the connection is closed immediately, without waiting for data to be flushed to the socket.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 the apparent remote address previously set bysetApparentRemoteAddress(SocketAddress)
, or the address returned bygetRemoteAddress()
if none was set.long
Returns 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.boolean
Returnstrue
if theconnect
event has ever executed.default boolean
boolean
Returnstrue
if this socket is connected.boolean
Returnstrue
if 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 SocketConnection
Adds an event listener for the given event.default SocketConnection
Adds 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.void
setApparentRemoteAddress
(SocketAddress apparentRemoteAddress) Sets a possibly different remote address a client claims to be or act on behalf of.default void
setOnClose
(org.omegazero.common.util.function.ThrowingRunnable onClose) Deprecated.default void
setOnConnect
(org.omegazero.common.util.function.ThrowingRunnable onConnect) Deprecated.Since 2.2.0, useon(String, GenericRunnable)
insteaddefault void
setOnData
(org.omegazero.common.util.function.ThrowingConsumer<byte[]> onData) Deprecated.Since 2.2.0, useon(String, GenericRunnable)
insteaddefault void
setOnError
(Consumer<Throwable> onError) Deprecated.Since 2.2.0, useon(String, GenericRunnable)
insteaddefault void
setOnTimeout
(org.omegazero.common.util.function.ThrowingRunnable onTimeout) Deprecated.Since 2.2.0, useon(String, GenericRunnable)
insteaddefault void
setOnWritable
(org.omegazero.common.util.function.ThrowingRunnable onWritable) Deprecated.Since 2.2.0, useon(String, GenericRunnable)
insteadvoid
setReadBlock
(boolean block) Enables or disables read blocking.default void
write
(byte[] data) Writes data to this connection for delivery to the peer host.void
write
(byte[] data, int offset, int length) Writes data to this connection for delivery to the peer host.default void
Writes the given string encoded usingUTF-8
to this connection for delivery to the peer host.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.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.
-
Method Details
-
connect
void connect(int timeout) Connects thisSocketConnection
to 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
timeout
event 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 theerror
event 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,
null
is returned, or the method blocks until data is available.- Returns:
- The read data or
null
if 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:writable
event).If this method is called before the
connect
event, 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-8
to 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:
true
if 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:
close
in interfaceAutoCloseable
- Specified by:
close
in 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 returnfalse
immediately 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()Returnstrue
if this socket is connected.- Returns:
true
if this socket is connected
-
hasConnected
boolean hasConnected()Returnstrue
if theconnect
event has ever executed. This is alreadytrue
while running the event.- Returns:
true
if theconnect
event has ever been emitted
-
hasDisconnected
default boolean hasDisconnected()- Returns:
true
if this socket has disconnected- Since:
- 1.6
-
isWritable
boolean isWritable()Returnstrue
if this socket is writable, meaning data passed towrite(byte[])
will not be buffered but written to the socket directly.- Returns:
true
if 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 tofalse
again. Note that the implementation may still emitdata
events 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, anerror
event is emitted instead. This event is followed by aclose
event 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 aclose
event.
An example for registering an event handler for the
data
event: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,
onError
is called instead. This callback is followed by aonClose
callback 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
onClose
callback.- Parameters:
onError
- The callback
-
on(String, GenericRunnable)
instead