Class SocketConnection

java.lang.Object
org.omegazero.net.socket.SocketConnection
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
ChannelConnection

public abstract class SocketConnection extends Object implements AutoCloseable
Represents any type of connection between the local and a remote host.
  • Field Details

    • readLock

      protected final Object readLock
      Lock for read operations.
    • writeLock

      protected final Object writeLock
      Lock for write operations.
  • Constructor Details

    • SocketConnection

      public SocketConnection()
  • Method Details

    • connect

      public abstract 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.

      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 the onError callback 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, null is returned.

      Returns:
      The read data or null if 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 onConnect 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

      public 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

      public 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:
      Implementation Note:
      The default behavior is to call write(byte[], int, int). Subclasses should override this method.
    • write

      public 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

      public abstract 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.
      Returns:
      true if 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:
      close in interface AutoCloseable
    • destroy

      public abstract 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.

    • isConnected

      public abstract boolean isConnected()
      Returns true if this socket is connected.
      Returns:
      true if this socket is connected
    • getRemoteAddress

      public abstract SocketAddress getRemoteAddress()
      Returns the address of the remote host.
      Returns:
      The address of the peer host
    • getLocalAddress

      public abstract SocketAddress 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 by System.currentTimeMillis().
      Returns:
      The last time any data was sent over this connection in milliseconds
    • isWritable

      public abstract 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

      public abstract 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 fire onData events while this option is set to true.
      Parameters:
      block - Whether to attempt to block incoming data
    • setApparentRemoteAddress

      public final 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

      public final 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
    • handleConnect

      public final void handleConnect()
    • handleTimeout

      public final void handleTimeout()
    • handleData

      public final boolean handleData(byte[] data)
      Called by classes managing this SocketConnection if data was received using read(). This method calls the onData callback.
      Parameters:
      data - The data that was received on this connection
      Returns:
      false if no onData handler was set
      See Also:
    • handleWritable

      public final void handleWritable()
      Called by subclasses if this socket is writable. This method calls the onWritable callback.
      See Also:
    • handleError

      public final void handleError(Throwable e)
      Called by subclasses or classes managing this SocketConnection if an error occurred in a callback. This method calls the onError callback and forcibly closes this connection.
      Parameters:
      e - The error
      Throws:
      UnhandledException - If no onError handler is set
      See Also:
    • handleClose

      public final void handleClose()
      Called by subclasses or classes managing this SocketConnection if this connection closed. This method calls the onError callback on the first invocation of this method.
      See Also:
    • setOnConnect

      public final void setOnConnect(ThrowingRunnable onConnect)
      Sets a callback that is called when this socket is connected and ready to receive or send data.
      Parameters:
      onConnect - The callback
    • setOnTimeout

      public final void setOnTimeout(ThrowingRunnable onTimeout)
      Sets a callback that is called when the connect operation started using connect(int) times out.
      Parameters:
      onTimeout - The callback
    • setOnData

      public final void setOnData(ThrowingConsumer<byte[]> onData)
      Sets a callback that is called when data is received on this connection.
      Parameters:
      onData - The callback
    • setOnWritable

      public final void setOnWritable(ThrowingRunnable onWritable)
      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

      public final void setOnClose(ThrowingRunnable onClose)
      Sets a callback that is called when this connection closes and can no longer receive or send data.
      Parameters:
      onClose - The callback
    • setOnError

      public final void setOnError(Consumer<Throwable> onError)
      Sets a callback that is called when an error occurs on this connection.

      This callback is usually followed by a onClose (set using SocketConnection#setOnClose(Runnable)) callback.

      Parameters:
      onError - The callback
    • setOnLocalClose

      public final void setOnLocalClose(Consumer<SocketConnection> onLocalClose)
    • setOnLocalConnect

      public final void setOnLocalConnect(Consumer<SocketConnection> onLocalConnect)
    • hasConnected

      public final boolean hasConnected()
      Returns true if the onConnect event has ever executed. This is already true while running the event.
      Returns:
      true if the onConnect event has ever fired
    • hasDisconnected

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

      protected final void localConnect()
      Called by implementing classes if this connection was established immediately upon calling connect(int). May be used internally by the connection manager.
    • localClose

      protected final void localClose()
      Called by implementing classes when this connection was closed using any close method (close() or destroy()).
    • 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

      public final Object getAttachment()
    • setAttachment

      public final void setAttachment(Object attachment)
    • getReadLock

      public Object 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

      public Object 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