Useful Methods of Socket Class

The following sections give a summary of important methods of Socket class.

1. Constructors

Socket()

Creates a raw socket which is not yet bound to a specific socket address (IP address and port). However, the binding may be done later using bind() method. The connection is not yet established to the server socket. However, the connection may be established later using connect() method.

Socket(InetAddress address, int port)

Creates a stream socket and connects to the server socket having specified address and port. The socket is also bound to an ephemeral port and a valid local address.

Socket(InetAddress host, int port, boolean stream)

This method is now deprecated. It is used to create stream as well as datagram socket. If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket. The socket is connected to the server socket having specified address and port.

Socket(InetAddress address, int port, InetAddress localAddr, int localPort) Creates a socket and connects to the server socket having specified address and port. The socket is bound to the specified localAddr and localPort. If a host has more than one IP address, this constructor is used to choose a specific IP address to bind the socket. If 0 (zero) is specified for port, system picks up an ephemeral port.

Socket(Proxy proxy)

Creates a socket which is not yet connected to a server socket. The connection may be made later using connect() method which consults specified proxy host to establish the connection. The proxy mechanism is useful if the client computer is not configured with a gateway and/or DNS host.

Socket(SocketImpl impl)

Creates a customized socket. The functionality of the socket is provided by the specified SocketImpl object. This SocketImpl class provides a plain implementation of the socket. Programmers who want to extend the functionality of a plain socket should create a class that extends SocketImpl class and override the methods defined in SocketImpl class.

Socket(String host, int port)

Creates a stream socket and connects to the specified port on the named host. The socket is also bound to an ephemeral port and a valid local address.

Socket(String host, int port, boolean stream)

This method is now deprecated also. It is used to create stream as well as datagram socket. If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket. The socket is connected to the specified port on the named host.

Socket(String host, int port, InetAddress localAddr, int localPort)

Creates a socket and connects to the specified port on the named host. The socket is bound to the specified localAddr and localPort. If a host has more than one IP address, this constructor is used to choose a specific IP address to bind the socket. If 0 (zero) is specified for port, system picks up an ephemeral port.

2. Methods

void bind(SocketAddress localEnd)

Binds the socket to the specified address (IP address and port). This method expects address as InetSocketAddress object. The InetSocketAddress class extends SocketAddress class and implements an IP Socket Address as [IP address, port number] or [hostname, port number] pair. In the latter case, an attempt will be made to resolve the hostname. If resolution fails then the address is said to be unresolved and a SocketException is thrown. However, the name can still be used on some circumstances such as connecting through a proxy. If the address is null, bind() picks up an ephemeral port and a valid local address to bind the socket.

void close()

Terminates the connection. Also closes the socket’s InputStream and OutputStream and hence the socket is not available for further networking. Accordingly, if there is any thread currently working on this socket, the thread throws a SocketException. A closed socket can never be rebound or reconnected. If required to, a new socket may be created instead. If the socket has an associated channel, the channel is also closed. void connect(SocketAddress address)

Connects the socket to the specified address (IP address and port) of the server socket. This method expects address as InetSocketAddress object. The InetSocketAddress class extends SocketAddress class and implements an IP Socket Address as [IP address, port number] or [hostname, port number] pair. In the latter case, an attempt will be made to resolve the hostname. If resolution fails then the address is said to be unresolved and a SocketException is thrown. However, the name can still be used on some circumstances such as connecting through a proxy.

void connect(SocketAddress address, int timeout)

Tries to connect this socket to the specified address for a specified time in milliseconds. If this method fails to establish a connection within this stipulated time, a SocketTimeoutException is thrown. A timeout of 0 (zero) indicates infinite timeout and in this case connect() blocks the caller until a connection is established or an error occurs.

SocketChannel getChannel()

Returns a SocketChannel object (if any) associated with this socket provided that the channel itself was created using static open() method of SocketChannel class.

InetAddress getInetAddress()

Returns the address of the server socket to which this socket is connected. It returns null if the socket is not connected.

InputStream getInputStream()

Returns an InputStream object that may be used to read data bytes from the socket through its read() method. The returned object is usually wrapped by other stream classes such as BufferedReader to receive data conveniently.

boolean getKeepAlive()

Returns a boolean indicating whether or not SocketOptions.SO_KEEPALIVE is enabled. InetAddress getLocalAddress()

Returns the address to which the socket is bound or null if the socket is not yet bound.

int getLocalPort()

Returns the port number this socket is bound. A value of -1 is returned if the socket is not yet bound.

SocketAddress getLocalSocketAddress()

Returns the socket address (IP address and port number) to which this socket is bound. The returned object is actually an InetSocketAddress object representing an IP address and a port number pair. Note that InetSocketAddress is a subclass of abstract SocketAddress class. The returned object is first converted to the InetSocketAddress type. To get the address and port, suitable methods on this resultant object may be used. This method returns a value null if the socket is not yet bound.

OutputStream getOutputStream()

Returns an OutputStream object that may be used to write data bytes to the socket through its write() method. The returned object is usually wrapped by other stream classes such as PrintWriter to send data conveniently.

int getPort()

Returns the port number of the server socket to which this socket is connected. A value of 0 (zero) is returned if this socket is not yet connected.

int getReceiveBufferSize()

Returns the value of the so_rcvbuf option for this Socket set by setReceiveBufferSize() method. The SO_RCVBUF option is the buffer size used by the platform for input on this Socket.

SocketAddress getRemoteSocketAddress()

Returns the socket address (IP address and port number) of the server socket to which this socket is connected. The returned object is actually an InetSocketAddress object representing an IP address and a port number pair. Note that InetSocketAddress is a subclass of abstract SocketAddress class. The returned object is first converted to the InetSocketAddress type. To get the address and port, suitable methods on this resultant object may be used. This method returns a value null if the socket is not yet connected.

boolean getReuseAddress()

Returns a true/false indicating whether or not so_reuseaddr is enabled/disabled.

int getSendBufferSize()

Returns the value of the so_sndbuf option for this Socket set by setSendBufferSize() method. The SO_SNDBUF option is the buffer size used by the platform for output on this Socket.

int getSoTimeout()

Returns SocketOptions.SO_TIMEOUT value. The value 0 indicates that timeout option is disabled (i.e. infinite timeout).

boolean getTcpNoDelay()

Returns true if the Nagle’s algorithm is enabled, false otherwise.

int getTrafficClass()

Returns traffic class or Type-of-Service (ToS) that was set by the setTrafficClass() method.

boolean isBound()

Returns true if the socket is successfully bound to a local socket address, false otherwise.

boolean isClosed()

Returns true if the socket is closed, false otherwise.

boolean isConnected()

Returns true if the socket is connected to a server socket successfully, false otherwise.

boolean isInputShutdown()

Returns true if the input stream of the socket is closed, false otherwise.

boolean isOutputShutdown()

Returns true if the output stream of the socket is closed, false otherwise.

void setKeepAlive(boolean on)

Sets the SocketOptions.SO_KEEPALIVE option to true or false. The purpose of this option is to detect if the peer host crashes or not. Setting this option to true instructs the system to check the status of the peer if no data has been exchanged across the socket in either direction for 2 hours (the actual value is implementation dependent). In this case, the TCP sends a keepalive probe to the peer who must respond. A response of ACK indicates that everything is fine and TCP understands the fact and does nothing but repeating the entire procedure after 2 hours of inactivity. If TCP gets a response RST (which indicates that the peer crashed and rebooted) or does not get any response, it closes the socket.

void setReceiveBufferSize(int size)

Sets the so_rcvbuf option for this socket to the specified value. The value of so_rcvbuf is used both to set the size of the internal socket receive buffer, and to set the size of the TCP receive window that is advertized to the remote peer.

void setReuseAddress(boolean on)

Sets SocketOptions.SO_REUSEADDR value to true or false. If a Socket object is closed using close() method, the connection is not closed and the address and port associated with the socket are not freed immediately. It may remain in a timeout state temporarily keeping the connection as it is. This state is known as time_wait state. Note that TCP provides in order delivery of packets. However, since the underlying IP layer does not provide any such guarantee on ordering, IP packets may arrive out of order. The task of TCP layer is to arrange them in the correct order and forward them to the application layer. So, out of order packets may arrive even if the connection is closed. That is why the connection is kept open (temporarily) so that delayed packets may be handled appropriately. So, time_wait state basically means that one side closed the connection but the final confirmation of the close is pending. The connection is finally terminated and all resources are freed. However, it may not be possible for an application to use the same address and port, if there is a connection in the time_wait state involving the address and port. The setReuseAddress() method may be used to enable/disable so_reuseaddr option prior to binding the socket using bind() to allow/disallow the socket to be bound even though a previous connection is in a time_wait state.

void setSendBufferSize(int size)

Sets the so_sndbuf option for this socket to the specified value. The so_sndbuf option is a hint for the size the platform’s networking code should use to set the underlying network I/O buffers.

static void setSocketImplFactory(SocketImplFactory fac)

This method is used to specify the client socket implementation factory for the application. The factory can be specified only once. When a new client socket is created, the createSocketImpl() method of socket implementation factory is called to create the actual socket implementation.

void setSoTimeout(int timeout)

Sets the SocketOptions.SO_TIMEOUT value with the specified timeout in milliseconds. If a non-zero timeout value is specified and subsequently read() method is called on InputStream associate with this socket, the read() method waits for only a specified amount of time for incoming data. If data comes within this specified time, a SocketTimeoutException is thrown. However, the socket remains valid and a different timeout value may be used (if required) later and read() method may also be called subsequently to have its effect. The timeout value is negative, an IllegalArgumentException is raised. A timeout value of 0 (which is also the default timeout) is used for infinite timeout.

void setTcpNoDelay(boolean on)

This method is used to enable/disable tcp_nodelay option of the socket. Thet tcp_nodelay option corresponds to the Nagle’s algorithm. Note that in this algorithm, written data to the network is not buffered which results in pending acknowledgement of previously written data.

void  setTrafficClass(int tc)

Sets traffic class or Type-of-Service (ToS) field in the IP header for packets sent from this socket to the specified value. It is just a hint as the underlying network implementation may ignore this value.

void shutdownInput ()

Sends the input stream for this socket to the end of stream state. As a result, any data sent to the input stream side of the socket is acknowledged and then discarded silently. Consequently, if we try to read data from a socket input stream after invoking this method on the socket, the stream will return eof.

void shutdownOutput()

Places the output stream for this socket to the disabled state. After invoking this method, any previously written data (for a TCP socket) will be sent followed by TCP’s normal connection termination sequence. Any attempt to write to a socket output stream after invoking shutdownOutput() on the socket, results in an IOException.

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *