Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.commons.net;
 
 import java.net.Proxy;
 
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 javax.net.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.

 
 public abstract class SocketClient
 {
    
The end of line character sequence used by most IETF protocols. That is a carriage return followed by a newline: "\r\n"
 
     public static final String NETASCII_EOL = "\r\n";

    
The default SocketFactory shared by all SocketClient instances.
 
     private static final SocketFactory __DEFAULT_SOCKET_FACTORY =
             SocketFactory.getDefault();

    
 
     private static final ServerSocketFactory __DEFAULT_SERVER_SOCKET_FACTORY =
             ServerSocketFactory.getDefault();

    
A ProtocolCommandSupport object used to manage the registering of ProtocolCommandListeners and the firing of ProtocolCommandEvents.
 
     private ProtocolCommandSupport __commandSupport;

    
The timeout to use after opening a socket.
 
     protected int _timeout_;

    
The socket used for the connection.
 
     protected Socket _socket_;

    
The default port the client should connect to.
 
     protected int _defaultPort_;

    
The socket's InputStream.
 
     protected InputStream _input_;

    
The socket's OutputStream.
 
     protected OutputStream _output_;

    
The socket's SocketFactory.
 
     protected SocketFactory _socketFactory_;

    
The socket's ServerSocket Factory.
 
     protected ServerSocketFactory _serverSocketFactory_;

    
The socket's connect timeout (0 = infinite timeout)
 
     private static final int DEFAULT_CONNECT_TIMEOUT = 0;
    protected int connectTimeout = ;

    
Hint for SO_RCVBUF size
    private int receiveBufferSize = -1;

    
Hint for SO_SNDBUF size
    private int sendBufferSize = -1;

    
The proxy to use when connecting.
    private Proxy connProxy;

    
Charset to use for byte IO.
    private Charset charset = Charset.defaultCharset();

    
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 org.apache.commons.net.DefaultSocketFactory.
    public SocketClient()
    {
         = null;
         = null;
         = null;
         = 0;
         = 0;
    }


    
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 of 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.

    protected void _connectAction_() throws IOException
    {
         = .getInputStream();
         = .getOutputStream();
    }


    
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:
java.net.SocketException If the socket timeout could not be set.
java.io.IOException If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
    public void connect(InetAddress hostint port)
    {
        if ( != -1) {
        }
        if ( != -1) {
            .setSendBufferSize();
        }
        .connect(new InetSocketAddress(hostport), );
        _connectAction_();
    }

    
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:
java.net.SocketException If the socket timeout could not be set.
java.io.IOException If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
java.net.UnknownHostException If the hostname cannot be resolved.
    public void connect(String hostnameint port)
    {
        connect(InetAddress.getByName(hostname), port);
    }


    
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:
java.net.SocketException If the socket timeout could not be set.
java.io.IOException If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
    public void connect(InetAddress hostint port,
                        InetAddress localAddrint localPort)
    {
        if ( != -1) {
        }
        if ( != -1) {
            .setSendBufferSize();
        }
        .bind(new InetSocketAddress(localAddrlocalPort));
        .connect(new InetSocketAddress(hostport), );
        _connectAction_();
    }


    
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:
java.net.SocketException If the socket timeout could not be set.
java.io.IOException If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
java.net.UnknownHostException If the hostname cannot be resolved.
    public void connect(String hostnameint port,
                        InetAddress localAddrint localPort)
    {
       connect(InetAddress.getByName(hostname), portlocalAddrlocalPort);
    }


    
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:
java.net.SocketException If the socket timeout could not be set.
java.io.IOException If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
    public void connect(InetAddress hostthrows SocketExceptionIOException
    {
        connect(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. Before returning, _connectAction_() is called to perform connection initialization actions.

Parameters:
hostname The name of the remote host.
Throws:
java.net.SocketException If the socket timeout could not be set.
java.io.IOException If the socket could not be opened. In most cases you will only want to catch IOException since SocketException is derived from it.
java.net.UnknownHostException If the hostname cannot be resolved.
    public void connect(String hostnamethrows SocketExceptionIOException
    {
        connect(hostname);
    }


    
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:
java.io.IOException If there is an error closing the socket.
    public void disconnect() throws IOException
    {
        closeQuietly();
        closeQuietly();
        closeQuietly();
         = null;
         = null;
         = null;
    }
    private void closeQuietly(Socket socket) {
        if (socket != null){
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
    private void closeQuietly(Closeable close){
        if (close != null){
            try {
                close.close();
            } catch (IOException e) {
            }
        }
    }
    
Returns true if the client is currently connected to a server.

Delegates to java.net.Socket.isConnected()

Returns:
True if the client is currently connected to a server, false otherwise.
    public boolean isConnected()
    {
        if ( == null) {
            return false;
        }
        return .isConnected();
    }

    
Make various checks on 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
Since:
3.0
See also:
NET-350
    public boolean isAvailable(){
        if (isConnected()) {
            try
            {
                if (.getInetAddress() == null) {
                    return false;
                }
                if (.getPort() == 0) {
                    return false;
                }
                if (.getRemoteSocketAddress() == null) {
                    return false;
                }
                if (.isClosed()) {
                    return false;
                }
                /* these aren't exact checks (a Socket can be half-open),
                   but since we usually require two-way data transfer,
                   we check these here too: */
                if (.isInputShutdown()) {
                    return false;
                }
                if (.isOutputShutdown()) {
                    return false;
                }
                /* ignore the result, catch exceptions: */
                .getInputStream();
                .getOutputStream();
            }
            catch (IOException ioex)
            {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    
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.
    public void setDefaultPort(int port)
    {
         = port;
    }

    
Returns the current value of the default port (stored in _defaultPort_ ).

Returns:
The current value of the default port.
    public int getDefaultPort()
    {
        return ;
    }


    
Set 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 an the currently opened socket. _timeout_ contains the new timeout value.

Parameters:
timeout The timeout in milliseconds to use for the socket connection.
    public void setDefaultTimeout(int timeout)
    {
         = timeout;
    }


    
Returns 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.
    public int getDefaultTimeout()
    {
        return ;
    }


    
Set 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:
java.net.SocketException If the operation fails.
java.lang.NullPointerException if the socket is not currently open
    public void setSoTimeout(int timeoutthrows SocketException
    {
        .setSoTimeout(timeout);
    }


    
Set the underlying socket send buffer size.

Parameters:
size The size of the buffer in bytes.
Throws:
java.net.SocketException
Since:
2.0
    public void setSendBufferSize(int sizethrows SocketException {
         = size;
    }

    
Get the current sendBuffer size

Returns:
the size, or -1 if not initialised
Since:
3.0
    protected int getSendBufferSize(){
        return ;
    }

    
Sets the underlying socket receive buffer size.

Parameters:
size The size of the buffer in bytes.
Throws:
java.net.SocketException
Since:
2.0
    public void setReceiveBufferSize(int sizethrows SocketException  {
         = size;
    }

    
Get the current receivedBuffer size

Returns:
the size, or -1 if not initialised
Since:
3.0
    protected int getReceiveBufferSize(){
        return ;
    }

    
Returns the timeout in milliseconds of the currently opened socket.

Returns:
The timeout in milliseconds of the currently opened socket.
Throws:
java.net.SocketException If the operation fails.
java.lang.NullPointerException if the socket is not currently open
    public int getSoTimeout() throws SocketException
    {
        return .getSoTimeout();
    }

    
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:
java.net.SocketException If the operation fails.
java.lang.NullPointerException if the socket is not currently open
    public void setTcpNoDelay(boolean onthrows SocketException
    {
        .setTcpNoDelay(on);
    }


    
Returns 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:
java.net.SocketException If the operation fails.
java.lang.NullPointerException if the socket is not currently open
    public boolean getTcpNoDelay() throws SocketException
    {
        return .getTcpNoDelay();
    }

    
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:
java.net.SocketException
java.lang.NullPointerException if the socket is not currently open
Since:
2.2
    public void setKeepAlive(boolean keepAlivethrows SocketException {
        .setKeepAlive(keepAlive);
    }

    
Returns the current value of the SO_KEEPALIVE flag on the currently opened socket. Delegates to java.net.Socket.getKeepAlive()

Returns:
True if SO_KEEPALIVE is enabled.
Throws:
java.net.SocketException
java.lang.NullPointerException if the socket is not currently open
Since:
2.2
    public boolean getKeepAlive() throws SocketException {
        return .getKeepAlive();
    }

    
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:
java.net.SocketException If the operation fails.
java.lang.NullPointerException if the socket is not currently open
    public void setSoLinger(boolean onint valthrows SocketException
    {
        .setSoLinger(onval);
    }


    
Returns the current SO_LINGER timeout of the currently opened socket.

Returns:
The current SO_LINGER timeout. If SO_LINGER is disabled returns -1.
Throws:
java.net.SocketException If the operation fails.
java.lang.NullPointerException if the socket is not currently open
    public int getSoLinger() throws SocketException
    {
        return .getSoLinger();
    }


    
Returns the port number of the open socket on the local host used for the connection. Delegates to java.net.Socket.getLocalPort()

Returns:
The port number of the open socket on the local host used for the connection.
Throws:
java.lang.NullPointerException if the socket is not currently open
    public int getLocalPort()
    {
        return .getLocalPort();
    }


    
Returns the local address to which the client's socket is bound. Delegates to java.net.Socket.getLocalAddress()

Returns:
The local address to which the client's socket is bound.
Throws:
java.lang.NullPointerException if the socket is not currently open
    public InetAddress getLocalAddress()
    {
        return .getLocalAddress();
    }

    
Returns the port number of the remote host to which the client is connected. Delegates to java.net.Socket.getPort()

Returns:
The port number of the remote host to which the client is connected.
Throws:
java.lang.NullPointerException if the socket is not currently open
    public int getRemotePort()
    {
        return .getPort();
    }


    

Returns:
The remote address to which the client is connected. Delegates to java.net.Socket.getInetAddress()
Throws:
java.lang.NullPointerException if the socket is not currently open
    public InetAddress getRemoteAddress()
    {
        return .getInetAddress();
    }


    
Verifies that the remote end of the given socket is connected to the 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.

Returns:
True if the remote hosts are the same, false if not.
    public boolean verifyRemote(Socket socket)
    {
        InetAddress host1host2;
        host1 = socket.getInetAddress();
        host2 = getRemoteAddress();
        return host1.equals(host2);
    }


    
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.
    public void setSocketFactory(SocketFactory factory)
    {
        if (factory == null) {
             = ;
        } else {
             = factory;
        }
        // re-setting the socket factory makes the proxy setting useless,
        // so set the field to null so that getProxy() doesn't return a
        // Proxy that we're actually not using.
         = null;
    }

    
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.
Since:
2.0
    public void setServerSocketFactory(ServerSocketFactory factory) {
        if (factory == null) {
        } else {
             = factory;
        }
    }

    
Sets the connection timeout in milliseconds, which will be passed to the java.net.Socket object's connect() method.

Parameters:
connectTimeout The connection timeout to use (in ms)
Since:
2.0
    public void setConnectTimeout(int connectTimeout) {
        this. = connectTimeout;
    }

    
Get the underlying socket connection timeout.

Returns:
timeout (in ms)
Since:
2.0
    public int getConnectTimeout() {
        return ;
    }

    
Get the underlying javax.net.ServerSocketFactory

Returns:
The server socket factory
Since:
2.2
        return ;
    }


    
Adds a ProtocolCommandListener.

Parameters:
listener The ProtocolCommandListener to add.
Since:
3.0
    public void addProtocolCommandListener(ProtocolCommandListener listener) {
    }

    
Removes a ProtocolCommandListener.

Parameters:
listener The ProtocolCommandListener to remove.
Since:
3.0
    public void removeProtocolCommandListener(ProtocolCommandListener listener) {
    }

    
If there are any listeners, send them the reply details.

Parameters:
replyCode the code extracted from the reply
reply the full reply text
Since:
3.0
    protected void fireReplyReceived(int replyCodeString reply) {
        if (getCommandSupport().getListenerCount() > 0) {
            getCommandSupport().fireReplyReceived(replyCodereply);
        }
    }

    
If there are any listeners, send them the command details.

Parameters:
command the command name
message the complete message, including command name
Since:
3.0
    protected void fireCommandSent(String commandString message) {
        if (getCommandSupport().getListenerCount() > 0) {
            getCommandSupport().fireCommandSent(commandmessage);
        }
    }

    
Create the CommandSupport instance if required
    protected void createCommandSupport(){
         = new ProtocolCommandSupport(this);
    }

    
Subclasses can override this if they need to provide their own instance field for backwards compatibilty.

Returns:
the CommandSupport instance, may be null
Since:
3.0
        return ;
    }

    
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.
Since:
3.2
    public void setProxy(Proxy proxy) {
        setSocketFactory(new DefaultSocketFactory(proxy));
         = proxy;
    }

    
Gets the proxy for use with all the connections.

Returns:
the current proxy for connections.
    public Proxy getProxy() {
        return ;
    }

    
Gets the charset name.

Returns:
the charset.
Since:
3.3 TODO Will be deprecated once the code requires Java 1.6 as a mininmum
    public String getCharsetName() {
        return .name();
    }

    
Gets the charset.

Returns:
the charset.
Since:
3.3
    public Charset getCharset() {
        return ;
    }

    
Sets the charset.

Parameters:
charset the charset.
Since:
3.3
    public void setCharset(Charset charset) {
        this. = charset;
    }
    /*
     *  N.B. Fields cannot be pulled up into a super-class without breaking binary compatibility,
     *  so the abstract method is needed to pass the instance to the methods which were moved here.
     */
New to GrepCode? Check out our FAQ X