Interface SocketConnection

All Superinterfaces:
AutoCloseable, Closeable
All Known Subinterfaces:
TLSConnection
All Known Implementing Classes:
AbstractSocketConnection, ChannelConnection, NioPlaintextConnection, NioTLSConnection

public interface SocketConnection extends Closeable
Represents any type of connection between the local and a remote host.

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 Details

    • connect

      void connect(int timeout)
      Connects this SocketConnection to the previously specified remote address in the constructor. If no address was specified, this method will throw an UnsupportedOperationException.

      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 the error 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 write
      offset - The start index of the data to write in the data byte array
      length - 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 to write(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 to write(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 write
      offset - The start index of the data to write in the data byte array
      length - 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

      default void write(String string)
      Writes the given string encoded using UTF-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 to writeQueue(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 interface AutoCloseable
      Specified by:
      close in interface Closeable
    • destroy

      void destroy()
      Similar to close(), except that the connection is closed immediately, without waiting for data to be flushed to the socket.

      isConnected() should return false 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 by System.currentTimeMillis().
      Returns:
      The last time any data was sent over this connection in milliseconds
    • isConnected

      boolean isConnected()
      Returns true if this socket is connected.
      Returns:
      true if this socket is connected
    • hasConnected

      boolean hasConnected()
      Returns true if the connect event has ever executed. This is already true while running the event.
      Returns:
      true if the connect event has ever been emitted
    • hasDisconnected

      default boolean hasDisconnected()
      Returns true if this socket has connected but is no longer connected.
      Returns:
      true if this socket has disconnected
      Since:
      1.6
    • isWritable

      boolean isWritable()
      Returns true if this socket is writable, meaning data passed to write(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 to true, the implementation will attempt to block incoming data from being processed and delay it until this is set to false again. Note that the implementation may still emit data events while this option is set to true.
      Parameters:
      block - Whether to attempt to block incoming data
    • setApparentRemoteAddress

      void setApparentRemoteAddress(SocketAddress apparentRemoteAddress)
      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 by setApparentRemoteAddress(SocketAddress), or the address returned by getRemoteAddress() if none was set.
      Returns:
      The apparent remote address
    • on

      SocketConnection on(String event, org.omegazero.common.event.runnable.GenericRunnable runnable)
      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 using connect(int) times out. If no listener is registered for this event, and a timeout occurs, an error event is emitted instead. This event is followed by a close event in both cases.
      • data(byte[]): Called when data is received on this connection.
      • writable(): Called when this socket is ready for writing after a write(byte[]) or connect(int) operation. This event is not emitted if the socket was previously already writable. This event is also not emitted during a write(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 a close event.

      An example for registering an event handler for the data event:

      
                      connection.on("data", (byte[] data) -> {
                              // ....
                      });
       
      Parameters:
      event - The event name
      runnable - The callback
      Returns:
      This SocketConnection
      Since:
      2.2.0
    • once

      SocketConnection once(String event, org.omegazero.common.event.runnable.GenericRunnable runnable)
      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 name
      runnable - The callback
      Returns:
      This SocketConnection
      Throws:
      UnsupportedOperationException - If single-event event listeners are not supported
      Since:
      2.2.0
    • off

      SocketConnection off(String event, org.omegazero.common.event.runnable.GenericRunnable runnable)
      Removes an event listener previously registered using on(String, GenericRunnable).
      Parameters:
      event - The event name
      runnable - 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 name
      runnable - 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 name
      runnable - 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, use on(String, GenericRunnable) instead
      Sets 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, use on(String, GenericRunnable) instead
      Sets a callback that is called when the connect operation started using connect(int) times out.

      If this callback is not set, and a timeout occurs, onError is called instead. This callback is followed by a onClose 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, use on(String, GenericRunnable) instead
      Sets 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, use on(String, GenericRunnable) instead
      Sets a callback that is called when this socket is ready for writing after a write(byte[]) or connect(int) operation. This event is not called if the socket was previously already writable. This event is also not called during a write(byte[]) call to allow the handler to safely call that method without being called again synchronously.
      Parameters:
      onWritable - The callback
    • setOnClose

      @Deprecated default void setOnClose(org.omegazero.common.util.function.ThrowingRunnable onClose)
      Deprecated.
      Since 2.2.0, use on(String, GenericRunnable) instead
      Sets a callback that is called when this connection closes and can no longer receive or send data.
      Parameters:
      onClose - The callback
    • setOnError

      @Deprecated default void setOnError(Consumer<Throwable> onError)
      Deprecated.
      Since 2.2.0, use on(String, GenericRunnable) instead
      Sets 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