org.apache.commons.net

## Class SocketClient

- java.lang.Object
- - org.apache.commons.net.SocketClient

- Direct Known Subclasses:
    CharGenTCPClient, DaytimeTCPClient, DiscardTCPClient, FingerClient, FTP, IMAP, NNTP, POP3, RExecClient, SMTP, Telnet, TimeTCPClient

      public abstract class SocketClient
      extends Object

  The SocketClient provides the basic operations that are required of client objects accessing sockets. It is meant to be subclassed to avoid having to rewrite the same code over and over again to open a socket, close a socket, set timeouts, etc. Of special note is the `setSocketFactory` method, which allows you to control the type of Socket the SocketClient creates for initiating network connections. This is especially useful for adding SSL or proxy support as well as better support for applets. For example, you could create a `SocketFactory` that requests browser security capabilities before creating a socket. All classes derived from SocketClient should use the `_socketFactory_` member variable to create Socket and ServerSocket instances rather than instantiating them by directly invoking a constructor. By honoring this contract you guarantee that a user will always be able to provide his own Socket implementations by substituting his own SocketFactory.
  See Also:
    `SocketFactory`

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected int` | `_defaultPort_` The default port the client should connect to.
    `protected String` | `_hostname_` The hostname used for the connection (null = no hostname supplied).
    `protected InputStream` | `_input_` The socket's InputStream.
    `protected OutputStream` | `_output_` The socket's OutputStream.
    `protected ServerSocketFactory` | `_serverSocketFactory_` The socket's ServerSocket Factory.
    `protected Socket` | `_socket_` The socket used for the connection.
    `protected SocketFactory` | `_socketFactory_` The socket's SocketFactory.
    `protected int` | `_timeout_` The timeout to use after opening a socket.
    `protected int` | `connectTimeout` Defaults to `DEFAULT_CONNECT_TIMEOUT`.
    `static String` | `NETASCII_EOL` The end of line character sequence used by most IETF protocols.
    `protected InetSocketAddress` | `remoteInetSocketAddress` The remote socket address used for the connection.

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `SocketClient()` Default constructor for SocketClient.

  - ### Method Summary

    All Methods Static Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `protected void` | `_connectAction_()` Because there are so many connect() methods, the _connectAction_() method is provided as a means of performing some action immediately after establishing a connection, rather than reimplementing all the connect() methods.
    `void` | `addProtocolCommandListener(ProtocolCommandListener listener)` Adds a ProtocolCommandListener.
    `protected void` | `applySocketAttributes()` Applies socket attributes.
    `protected OutputStream` | `checkOpenOutputStream()` Gets the non-null OutputStream or throws `NullPointerException`.
    `void` | `connect(InetAddress host)` Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port.
    `void` | `connect(InetAddress host, int port)` Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.
    `void` | `connect(InetAddress host, int port, InetAddress localAddr, int localPort)` Opens a Socket connected to a remote host at the specified port and originating from the specified local address and port.
    `void` | `connect(String hostname)` Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port.
    `void` | `connect(String hostname, int port)` Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.
    `void` | `connect(String hostname, int port, InetAddress localAddr, int localPort)` Opens a Socket connected to a remote host at the specified port and originating from the specified local address and port.
    `protected void` | `createCommandSupport()` Create the CommandSupport instance if required
    `void` | `disconnect()` Disconnects the socket connection.
    `protected void` | `fireCommandSent(String command, String message)` If there are any listeners, send them the command details.
    `protected void` | `fireReplyReceived(int replyCode, String reply)` If there are any listeners, send them the reply details.
    `Charset` | `getCharset()` Gets the charset.
    `protected ProtocolCommandSupport` | `getCommandSupport()` Subclasses can override this if they need to provide their own instance field for backwards compatibility.
    `int` | `getConnectTimeout()` Gets the underlying socket connection timeout.
    `int` | `getDefaultPort()` Gets the current value of the default port (stored in `_defaultPort_`).
    `int` | `getDefaultTimeout()` Gets the default timeout in milliseconds that is used when opening a socket.
    `protected static String` | `getHostAddress(InetAddress inetAddress)` Gets the IP address string of the given InetAddress in textual presentation.
    `protected static String` | `getHostAddress(Socket socket)` Gets the IP address string of the given Socket in textual presentation.
    `boolean` | `getKeepAlive()` Gets the current value of the SO_KEEPALIVE flag on the currently opened socket.
    `InetAddress` | `getLocalAddress()` Gets the local address to which the client's socket is bound.
    `int` | `getLocalPort()` Gets the port number of the open socket on the local host used for the connection.
    `Proxy` | `getProxy()` Gets the proxy for use with all the connections.
    `protected int` | `getReceiveBufferSize()` Gets the current receivedBuffer size
    `InetAddress` | `getRemoteAddress()` Gets the address to which the socket is connected.
    `protected InetSocketAddress` | `getRemoteInetSocketAddress()` Gets the remote socket address used for the connection.
    `int` | `getRemotePort()` Gets the port number of the remote host to which the client is connected.
    `protected int` | `getSendBufferSize()` Gets the current sendBuffer size
    `ServerSocketFactory` | `getServerSocketFactory()` Gets the underlying `ServerSocketFactory`
    `int` | `getSoLinger()` Gets the current SO_LINGER timeout of the currently opened socket.
    `int` | `getSoTimeout()` Gets the timeout in milliseconds of the currently opened socket.
    `boolean` | `getTcpNoDelay()` Gets true if Nagle's algorithm is enabled on the currently opened socket.
    `boolean` | `isAvailable()` Tests the socket to test if it is available for use.
    `boolean` | `isConnected()` Tests whether the client is currently connected to a server.
    `void` | `removeProtocolCommandListener(ProtocolCommandListener listener)` Removes a ProtocolCommandListener.
    `void` | `setCharset(Charset charset)` Sets the charset.
    `void` | `setConnectTimeout(int connectTimeout)` Sets the connection timeout in milliseconds, which will be passed to the `Socket` object's connect() method.
    `void` | `setDefaultPort(int port)` Sets the default port the SocketClient should connect to when a port is not specified.
    `void` | `setDefaultTimeout(int timeout)` Sets the default timeout in milliseconds to use when opening a socket.
    `void` | `setKeepAlive(boolean keepAlive)` Sets the SO_KEEPALIVE flag on the currently opened socket.
    `void` | `setProxy(Proxy proxy)` Sets the proxy for use with all the connections.
    `void` | `setReceiveBufferSize(int size)` Sets the underlying socket receive buffer size.
    `void` | `setSendBufferSize(int size)` Sets the underlying socket send buffer size.
    `void` | `setServerSocketFactory(ServerSocketFactory factory)` Sets the ServerSocketFactory used by the SocketClient to open ServerSocket connections.
    `void` | `setSocketFactory(SocketFactory factory)` Sets the SocketFactory used by the SocketClient to open socket connections.
    `void` | `setSoLinger(boolean on, int val)` Sets the SO_LINGER timeout on the currently opened socket.
    `void` | `setSoTimeout(int timeout)` Sets the timeout in milliseconds of a currently open connection.
    `void` | `setTcpNoDelay(boolean on)` Enables or disables the Nagle's algorithm (TCP_NODELAY) on the currently opened socket.
    `boolean` | `verifyRemote(Socket socket)` Verifies that the remote end of the given socket is connected to the same host that the SocketClient is currently connected to.

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### _defaultPort_

          protected int _defaultPort_

      The default port the client should connect to.

    - #### _hostname_

          protected String _hostname_

      The hostname used for the connection (null = no hostname supplied).

    - #### _input_

          protected InputStream _input_

      The socket's InputStream.

    - #### _output_

          protected OutputStream _output_

      The socket's OutputStream.

    - #### _serverSocketFactory_

          protected ServerSocketFactory _serverSocketFactory_

      The socket's ServerSocket Factory.

    - #### _socket_

          protected Socket _socket_

      The socket used for the connection.

    - #### _socketFactory_

          protected SocketFactory _socketFactory_

      The socket's SocketFactory.

    - #### _timeout_

          protected int _timeout_

      The timeout to use after opening a socket.

    - #### connectTimeout

          protected int connectTimeout

      Defaults to `DEFAULT_CONNECT_TIMEOUT`.

    - #### NETASCII_EOL

          public static final String NETASCII_EOL

      The end of line character sequence used by most IETF protocols. That is a carriage return followed by a newline: "\r\n"
      See Also:
        Constant Field Values

    - #### remoteInetSocketAddress

          protected InetSocketAddress remoteInetSocketAddress

      The remote socket address used for the connection.

  - ### Constructor Detail

    - #### SocketClient

          public SocketClient()

      Default constructor for SocketClient. Initializes _socket_ to null, _timeout_ to 0, _defaultPort to 0, _isConnected_ to false, charset to `Charset.defaultCharset()` and _socketFactory_ to a shared instance of `DefaultSocketFactory`.

  - ### Method Detail

    - #### _connectAction_

          protected void _connectAction_()
                                  throws IOException

      Because there are so many connect() methods, the _connectAction_() method is provided as a means of performing some action immediately after establishing a connection, rather than reimplementing all the connect() methods. The last action performed by every connect() method after opening a socket is to call this method.

      This method sets the timeout on the just opened socket to the default timeout set by `setDefaultTimeout()`, sets _input_ and _output_ to the socket's InputStream and OutputStream respectively, and sets _isConnected_ to true.

      Subclasses overriding this method should start by calling `super._connectAction_()` first to ensure the initialization of the aforementioned protected variables.

      Throws:
        `IOException` - (SocketException) if a problem occurs with the socket

    - #### addProtocolCommandListener

          public void addProtocolCommandListener(ProtocolCommandListener listener)

      Adds a ProtocolCommandListener.
      Parameters:
        `listener` - The ProtocolCommandListener to add.

    - #### applySocketAttributes

          protected void applySocketAttributes()
                                        throws SocketException

      Applies socket attributes.
      Throws:
        `SocketException` - if there is an error in the underlying protocol, such as a TCP error.

    - #### checkOpenOutputStream

          protected OutputStream checkOpenOutputStream()

      Gets the non-null OutputStream or throws `NullPointerException`.

      This method does not allocate resources.

      Returns:
        the non-null OutputStream.

    - #### connect

          public void connect(InetAddress host)
                       throws SocketException,
                              IOException

      Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port. Before returning, `_connectAction_()` is called to perform connection initialization actions.
      Parameters:
        `host` - The remote host.
      Throws:
        `SocketException` - If the socket timeout could not be set.
        `IOException` - If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.

    - #### connect

          public void connect(InetAddress host,
                              int port)
                       throws SocketException,
                              IOException

      Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port. Before returning, `_connectAction_()` is called to perform connection initialization actions.
      Parameters:
        `host` - The remote host.
        `port` - The port to connect to on the remote host.
      Throws:
        `SocketException` - If the socket timeout could not be set.
        `IOException` - If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.

    - #### connect

          public void connect(InetAddress host,
                              int port,
                              InetAddress localAddr,
                              int localPort)
                       throws SocketException,
                              IOException

      Opens a Socket connected to a remote host at the specified port and originating from the specified local address and port. Before returning, `_connectAction_()` is called to perform connection initialization actions.
      Parameters:
        `host` - The remote host.
        `port` - The port to connect to on the remote host.
        `localAddr` - The local address to use.
        `localPort` - The local port to use.
      Throws:
        `SocketException` - If the socket timeout could not be set.
        `IOException` - If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.

    - #### connect

          public void connect(String hostname)
                       throws SocketException,
                              IOException

      Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port. Before returning, `_connectAction_()` is called to perform connection initialization actions.
      Parameters:
        `hostname` - The name of the remote host.
      Throws:
        `SocketException` - If the socket timeout could not be set.
        `IOException` - If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
        `UnknownHostException` - If the hostname cannot be resolved.

    - #### connect

          public void connect(String hostname,
                              int port)
                       throws SocketException,
                              IOException

      Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port. Before returning, `_connectAction_()` is called to perform connection initialization actions.
      Parameters:
        `hostname` - The name of the remote host.
        `port` - The port to connect to on the remote host.
      Throws:
        `SocketException` - If the socket timeout could not be set.
        `IOException` - If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
        `UnknownHostException` - If the hostname cannot be resolved.

    - #### connect

          public void connect(String hostname,
                              int port,
                              InetAddress localAddr,
                              int localPort)
                       throws SocketException,
                              IOException

      Opens a Socket connected to a remote host at the specified port and originating from the specified local address and port. Before returning, `_connectAction_()` is called to perform connection initialization actions.
      Parameters:
        `hostname` - The name of the remote host.
        `port` - The port to connect to on the remote host.
        `localAddr` - The local address to use.
        `localPort` - The local port to use.
      Throws:
        `SocketException` - If the socket timeout could not be set.
        `IOException` - If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
        `UnknownHostException` - If the hostname cannot be resolved.

    - #### createCommandSupport

          protected void createCommandSupport()

      Create the CommandSupport instance if required

    - #### disconnect

          public void disconnect()
                          throws IOException

      Disconnects the socket connection. You should call this method after you've finished using the class instance and also before you call `connect()` again. _isConnected_ is set to false, _socket_ is set to null, _input_ is set to null, and _output_ is set to null.
      Throws:
        `IOException` - not thrown, subclasses may throw.

    - #### fireCommandSent

          protected void fireCommandSent(String command,
                                         String message)

      If there are any listeners, send them the command details.
      Parameters:
        `command` - the command name
        `message` - the complete message, including command name

    - #### fireReplyReceived

          protected void fireReplyReceived(int replyCode,
                                           String reply)

      If there are any listeners, send them the reply details.
      Parameters:
        `replyCode` - the code extracted from the reply
        `reply` - the full reply text

    - #### getCharset

          public Charset getCharset()

      Gets the charset.
      Returns:
        the charset.

    - #### getCommandSupport

          protected ProtocolCommandSupport getCommandSupport()

      Subclasses can override this if they need to provide their own instance field for backwards compatibility.
      Returns:
        the CommandSupport instance, may be `null`

    - #### getConnectTimeout

          public int getConnectTimeout()

      Gets the underlying socket connection timeout.
      Returns:
        timeout (in ms)

    - #### getDefaultPort

          public int getDefaultPort()

      Gets the current value of the default port (stored in `_defaultPort_`).
      Returns:
        The current value of the default port.

    - #### getDefaultTimeout

          public int getDefaultTimeout()

      Gets the default timeout in milliseconds that is used when opening a socket.
      Returns:
        The default timeout in milliseconds that is used when opening a socket.

    - #### getHostAddress

          protected static String getHostAddress(InetAddress inetAddress)

      Gets the IP address string of the given InetAddress in textual presentation.
      Parameters:
        `inetAddress` - Internet Protocol (IP) address to query.
      Returns:
        the raw IP address in a string format.

    - #### getHostAddress

          protected static String getHostAddress(Socket socket)

      Gets the IP address string of the given Socket in textual presentation.
      Parameters:
        `socket` - the socket to query.
      Returns:
        the raw IP address in a string format.

    - #### getKeepAlive

          public boolean getKeepAlive()
                               throws SocketException

      Gets the current value of the SO_KEEPALIVE flag on the currently opened socket. Delegates to `Socket.getKeepAlive()`
      Returns:
        True if SO_KEEPALIVE is enabled.
      Throws:
        `SocketException` - if there is a problem with the socket
        `NullPointerException` - if the socket is not currently open

    - #### getLocalAddress

          public InetAddress getLocalAddress()

      Gets the local address to which the client's socket is bound. Delegates to `Socket.getLocalAddress()`
      Returns:
        The local address to which the client's socket is bound.
      Throws:
        `NullPointerException` - if the socket is not currently open

    - #### getLocalPort

          public int getLocalPort()

      Gets the port number of the open socket on the local host used for the connection. Delegates to `Socket.getLocalPort()`
      Returns:
        The port number of the open socket on the local host used for the connection.
      Throws:
        `NullPointerException` - if the socket is not currently open

    - #### getProxy

          public Proxy getProxy()

      Gets the proxy for use with all the connections.
      Returns:
        the current proxy for connections.

    - #### getReceiveBufferSize

          protected int getReceiveBufferSize()

      Gets the current receivedBuffer size
      Returns:
        the size, or -1 if not initialized

    - #### getRemoteAddress

          public InetAddress getRemoteAddress()

      Gets the address to which the socket is connected.
      Returns:
        The remote address to which the client is connected. Delegates to `Socket.getInetAddress()`
      Throws:
        `NullPointerException` - if the socket is not currently open

    - #### getRemoteInetSocketAddress

          protected InetSocketAddress getRemoteInetSocketAddress()

      Gets the remote socket address used for the connection.
      Returns:
        the remote socket address used for the connection

    - #### getRemotePort

          public int getRemotePort()

      Gets the port number of the remote host to which the client is connected. Delegates to `Socket.getPort()`
      Returns:
        The port number of the remote host to which the client is connected.
      Throws:
        `NullPointerException` - if the socket is not currently open

    - #### getSendBufferSize

          protected int getSendBufferSize()

      Gets the current sendBuffer size
      Returns:
        the size, or -1 if not initialized

    - #### getServerSocketFactory

          public ServerSocketFactory getServerSocketFactory()

      Gets the underlying `ServerSocketFactory`
      Returns:
        The server socket factory

    - #### getSoLinger

          public int getSoLinger()
                          throws SocketException

      Gets the current SO_LINGER timeout of the currently opened socket.
      Returns:
        The current SO_LINGER timeout. If SO_LINGER is disabled returns -1.
      Throws:
        `SocketException` - If the operation fails.
        `NullPointerException` - if the socket is not currently open

    - #### getSoTimeout

          public int getSoTimeout()
                           throws SocketException

      Gets the timeout in milliseconds of the currently opened socket.
      Returns:
        The timeout in milliseconds of the currently opened socket.
      Throws:
        `SocketException` - If the operation fails.
        `NullPointerException` - if the socket is not currently open

    - #### getTcpNoDelay

          public boolean getTcpNoDelay()
                                throws SocketException

      Gets true if Nagle's algorithm is enabled on the currently opened socket.
      Returns:
        True if Nagle's algorithm is enabled on the currently opened socket, false otherwise.
      Throws:
        `SocketException` - If the operation fails.
        `NullPointerException` - if the socket is not currently open

    - #### isAvailable

          public boolean isAvailable()

      Tests the socket to test if it is available for use. Note that the only sure test is to use it, but these checks may help in some cases.
      Returns:
        `true` if the socket appears to be available for use
      See Also:
        NET-350

    - #### isConnected

          public boolean isConnected()

      Tests whether the client is currently connected to a server. Delegates to `Socket.isConnected()`
      Returns:
        True if the client is currently connected to a server, false otherwise.

    - #### removeProtocolCommandListener

          public void removeProtocolCommandListener(ProtocolCommandListener listener)

      Removes a ProtocolCommandListener.
      Parameters:
        `listener` - The ProtocolCommandListener to remove.

    - #### setCharset

          public void setCharset(Charset charset)

      Sets the charset.
      Parameters:
        `charset` - the charset.

    - #### setConnectTimeout

          public void setConnectTimeout(int connectTimeout)

      Sets the connection timeout in milliseconds, which will be passed to the `Socket` object's connect() method.
      Parameters:
        `connectTimeout` - The connection timeout to use (in ms)

    - #### setDefaultPort

          public void setDefaultPort(int port)

      Sets the default port the SocketClient should connect to when a port is not specified. The `_defaultPort_` variable stores this value. If never set, the default port is equal to zero.
      Parameters:
        `port` - The default port to set.

    - #### setDefaultTimeout

          public void setDefaultTimeout(int timeout)

      Sets the default timeout in milliseconds to use when opening a socket. This value is only used previous to a call to `connect()` and should not be confused with `setSoTimeout()` which operates on the currently opened socket. _timeout_ contains the new timeout value.
      Parameters:
        `timeout` - The timeout in milliseconds to use for the socket connection.

    - #### setKeepAlive

          public void setKeepAlive(boolean keepAlive)
                            throws SocketException

      Sets the SO_KEEPALIVE flag on the currently opened socket. From the Javadocs, the default keepalive time is 2 hours (although this is implementation dependent). It looks as though the Windows WSA sockets implementation allows a specific keepalive value to be set, although this seems not to be the case on other systems.
      Parameters:
        `keepAlive` - If true, keepAlive is turned on
      Throws:
        `SocketException` - if there is a problem with the socket
        `NullPointerException` - if the socket is not currently open

    - #### setProxy

          public void setProxy(Proxy proxy)

      Sets the proxy for use with all the connections. The proxy is used for connections established after the call to this method.
      Parameters:
        `proxy` - the new proxy for connections.

    - #### setReceiveBufferSize

          public void setReceiveBufferSize(int size)
                                    throws SocketException

      Sets the underlying socket receive buffer size.
      Parameters:
        `size` - The size of the buffer in bytes.
      Throws:
        `SocketException` - never (but subclasses may wish to do so)

    - #### setSendBufferSize

          public void setSendBufferSize(int size)
                                 throws SocketException

      Sets the underlying socket send buffer size.
      Parameters:
        `size` - The size of the buffer in bytes.
      Throws:
        `SocketException` - never thrown, but subclasses might want to do so

    - #### setServerSocketFactory

          public void setServerSocketFactory(ServerSocketFactory factory)

      Sets the ServerSocketFactory used by the SocketClient to open ServerSocket connections. If the factory value is null, then a default factory is used (only do this to reset the factory after having previously altered it).
      Parameters:
        `factory` - The new ServerSocketFactory the SocketClient should use.

    - #### setSocketFactory

          public void setSocketFactory(SocketFactory factory)

      Sets the SocketFactory used by the SocketClient to open socket connections. If the factory value is null, then a default factory is used (only do this to reset the factory after having previously altered it). Any proxy setting is discarded.
      Parameters:
        `factory` - The new SocketFactory the SocketClient should use.

    - #### setSoLinger

          public void setSoLinger(boolean on,
                                  int val)
                           throws SocketException

      Sets the SO_LINGER timeout on the currently opened socket.
      Parameters:
        `on` - True if linger is to be enabled, false if not.
        `val` - The `linger` timeout (in hundredths of a second?)
      Throws:
        `SocketException` - If the operation fails.
        `NullPointerException` - if the socket is not currently open

    - #### setSoTimeout

          public void setSoTimeout(int timeout)
                            throws SocketException

      Sets the timeout in milliseconds of a currently open connection. Only call this method after a connection has been opened by `connect()`.

      To set the initial timeout, use `setDefaultTimeout(int)` instead.

      Parameters:
        `timeout` - The timeout in milliseconds to use for the currently open socket connection.
      Throws:
        `SocketException` - If the operation fails.
        `NullPointerException` - if the socket is not currently open

    - #### setTcpNoDelay

          public void setTcpNoDelay(boolean on)
                             throws SocketException

      Enables or disables the Nagle's algorithm (TCP_NODELAY) on the currently opened socket.
      Parameters:
        `on` - True if Nagle's algorithm is to be enabled, false if not.
      Throws:
        `SocketException` - If the operation fails.
        `NullPointerException` - if the socket is not currently open

    - #### verifyRemote

          public boolean verifyRemote(Socket socket)

      Verifies that the remote end of the given socket is connected to the same host that the SocketClient is currently connected to. This is useful for doing a quick security check when a client needs to accept a connection from a server, such as an FTP data connection or a BSD R command standard error stream.
      Parameters:
        `socket` - the item to check against
      Returns:
        True if the remote hosts are the same, false if not.