Socket class in Java

java.net.Socket

This class implements client sockets (also called just"sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. By changing the socket factory that creates the socket implementation, an application can configure itself to create sockets appropriate to the local firewall.

The Socket class defines convenience methods to set and get several socket options. This class also defines the setOptionand getOption methods to set and query socket options.

Socket supports the following options:

Option Name                                       Description

SO_SNDBUF                              The size of the socket sends the buffer

SO_RCVBUF                              The size of the socket receives the buffer

SO_KEEPALIVE                         Keep connection alive

SO_REUSEADDR                      Re-use address

SO_LINGER                               Linger on close if data is present (when configured                                                      in blocking mode only)

TCP_NODELAY                          Disable the Nagle algorithm Additional                                                                        (implementation-specific) options may also be supported.

Some methods of Socket class

Socket()This method creates an unconnected Socket.

Socket(Proxy)This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of other settings.

Socket(InetAddress, int)This method creates a stream socket and connects it to the specified port number at the specified IP address.

Socket(String, int)This method creates a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress, int, InetAddress, int)This method creates a socket and connects it to the specified remote address on the specified remote port. The Socket will bind() to the local address and port supplied.

Socket(String, int, InetAddress, int)This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will bind() to the local address and port supplied.

bind(SocketAddress) This method binds the socket to a local address.

close()This method closes this socket.

connect(SocketAddress)This method connects this socket to the server.

connect(SocketAddress, int)This method connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout.

getChannel()This method returns the unique SocketChannelobject associated with this socket, if any.

getInetAddress()This method returns the address to which the socket is connected.

getInputStream()This method returns an input stream for this socket.

getKeepAlive()This method tests if SO_KEEPALIVE is enabled.

getLocalAddress()This method gets the local address to which the socket is bound.

getLocalPort()This method returns the local port number to which this socket is bound.

getLocalSocketAddress()This method returns the address of the endpoint this socket is bound to.

getOOBInline()This method tests if SO_OOBINLINE is enabled.

getOption(SocketOption)This method returns the value of a socket option.

getOutputStream()This method returns an output stream for this socket.

getPort()This method returns the remote port number to which this socket is connected.

getReceiveBufferSize()This method gets the value of the SO_RCVBUF option for this Socket, which is the buffer size used by the platform for input on this Socket.

getRemoteSocketAddress()This method returns the address of the endpoint this socket is connected to, or null if it is unconnected.

getReuseAddress()This method tests if SO_REUSEADDR is enabled.

getSendBufferSize()This method gets the value of the SO_SNDBUF option for this Socket, which is the buffer size used by the platform for output on this Socket.

getSoLinger()This method returns the setting for SO_LINGER.-1 returns implies that the option is disabled. The setting only affects socket closing.

getSoTimeout()This method returns setting for SO_TIMEOUT.0 returns implies that the option is disabled (i.e., timeout of infinity).

getTcpNoDelay()This method tests if TCP_NODELAY is enabled.

getTrafficClass()This method gets the traffic class or type of service in the IP header for packets sent from this Socket.

isBound()This method returns the binding state of the socket.

isClosed()This method returns the closed state of the socket.

isConnected()This method returns the connection state of the socket.

isInputShutdown()This method returns whether the read-half of the socket connection is closed.

isOutputShutdown()This method returns whether the write-half of the socket connection is closed.

sendUrgentData(int)This method sends one byte of urgent data to the socket. The byte to be sent is the lowest eight bits of the data parameter.

setKeepAlive(boolean)This method enables/disables SO_KEEPALIVE.

setOOBInline(boolean) This method enables/disables SO_OOBINLINE By default, this option is disabled, and TCP urgent data received on a socket is silently discarded.

setOption(SocketOption, Object)This method sets the value of a socket option.

setPerformancePreferences(int, int, int)This method sets performance preferences for this socket.

setReceiveBufferSize(int)This method sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

setReuseAddress(boolean)This method enables/disables the SO_REUSEADDR socket option.

setSendBufferSize(int)This method sets the SO_SNDBUF option to the specified value for this Socket. 

Socket.setSocketImplFactory(SocketImplFactory) This method sets the client socket implementation factory for the application. The factory can be specified only once.

setSoLinger(boolean, int)This method enables/disables SO_LINGER with the specified linger time in seconds.

setSoTimeout(int)This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds.

setTcpNoDelay(boolean)This method enables/disables TCP_NODELAY (disable/enable Nagle's algorithm).

setTrafficClass(int)This method sets the traffic class or type-of-service octet in the IP header for packets sent from this Socket.

shutdownInput()This method places the input stream for this socket at the "end of stream".

shutdownOutput()This method disables the output stream for this socket.

supportedOptions()This method returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

toString()This method converts this socket to a String.

Socket toString() in Java

toString(): This method is available in the java.net.Socket class of Java.

Syntax:

String java.net.Socket.toString()

This method converts this socket to a String.

Parameters: NA

Returns: a string representation of this socket.

Exceptions: NA

Approach

Java

package com.Socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class SockettoString {
    public static void main(String[] args) throws IOException {

        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;

        Socket socket = new Socket(addr, port);

        System.out.println(socket.toString());
        socket.close();
    }
}

Output:

Socket[addr=java.sun.com/23.54.83.211,port=80,localport=65211]


Some other methods of Socket class

Socket()This method creates an unconnected Socket.

Socket(Proxy)This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of other settings.

Socket(InetAddress, int)This method creates a stream socket and connects it to the specified port number at the specified IP address.

Socket(String, int)This method creates a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress, int, InetAddress, int)This method creates a socket and connects it to the specified remote address on the specified remote port. The Socket will bind() to the local address and port supplied.

Socket(String, int, InetAddress, int)This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will bind() to the local address and port supplied.

bind(SocketAddress) This method binds the socket to a local address.

close()This method closes this socket.

connect(SocketAddress)This method connects this socket to the server.

connect(SocketAddress, int)This method connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout.

getChannel()This method returns the unique SocketChannelobject associated with this socket, if any.

getInetAddress()This method returns the address to which the socket is connected.

getInputStream()This method returns an input stream for this socket.

getKeepAlive()This method tests if SO_KEEPALIVE is enabled.

getLocalAddress()This method gets the local address to which the socket is bound.

getLocalPort()This method returns the local port number to which this socket is bound.

getLocalSocketAddress()This method returns the address of the endpoint this socket is bound to.

getOOBInline()This method tests if SO_OOBINLINE is enabled.

getOption(SocketOption)This method returns the value of a socket option.

getOutputStream()This method returns an output stream for this socket.

getPort()This method returns the remote port number to which this socket is connected.

getReceiveBufferSize()This method gets the value of the SO_RCVBUF option for this Socket, which is the buffer size used by the platform for input on this Socket.

getRemoteSocketAddress()This method returns the address of the endpoint this socket is connected to, or null if it is unconnected.

getReuseAddress()This method tests if SO_REUSEADDR is enabled.

getSendBufferSize()This method gets the value of the SO_SNDBUF option for this Socket, which is the buffer size used by the platform for output on this Socket.

getSoLinger()This method returns the setting for SO_LINGER.-1 returns implies that the option is disabled. The setting only affects socket closing.

getSoTimeout()This method returns setting for SO_TIMEOUT.0 returns implies that the option is disabled (i.e., timeout of infinity).

getTcpNoDelay()This method tests if TCP_NODELAY is enabled.

getTrafficClass()This method gets the traffic class or type of service in the IP header for packets sent from this Socket.

isBound()This method returns the binding state of the socket.

isClosed()This method returns the closed state of the socket.

isConnected()This method returns the connection state of the socket.

isInputShutdown()This method returns whether the read-half of the socket connection is closed.

isOutputShutdown()This method returns whether the write-half of the socket connection is closed.

sendUrgentData(int)This method sends one byte of urgent data to the socket. The byte to be sent is the lowest eight bits of the data parameter.

setKeepAlive(boolean)This method enables/disables SO_KEEPALIVE.

setOOBInline(boolean) This method enables/disables SO_OOBINLINE By default, this option is disabled, and TCP urgent data received on a socket is silently discarded.

setOption(SocketOption, Object)This method sets the value of a socket option.

setPerformancePreferences(int, int, int)This method sets performance preferences for this socket.

setReceiveBufferSize(int)This method sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

setReuseAddress(boolean)This method enables/disables the SO_REUSEADDR socket option.

setSendBufferSize(int)This method sets the SO_SNDBUF option to the specified value for this Socket. 

Socket.setSocketImplFactory(SocketImplFactory) This method sets the client socket implementation factory for the application. The factory can be specified only once.

setSoLinger(boolean, int)This method enables/disables SO_LINGER with the specified linger time in seconds.

setSoTimeout(int)This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds.

setTcpNoDelay(boolean)This method enables/disables TCP_NODELAY (disable/enable Nagle's algorithm).

setTrafficClass(int)This method sets the traffic class or type-of-service octet in the IP header for packets sent from this Socket.

shutdownInput()This method places the input stream for this socket at the "end of stream".

shutdownOutput()This method disables the output stream for this socket.

supportedOptions()This method returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

toString()This method converts this socket to a String.

Socket supportedOptions() in Java

supportedOptions(): This method is available in the java.net.Socket class of Java.

Syntax:

Set<SocketOption<?>> java.net.Socket.supportedOptions()

This method returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

Parameters: NA

Returns: A set of the socket options supported by this socket. This set may be empty if the socket's SocketImpl cannot be created.

Exceptions: NA

Approach

Java

package com.Socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class SocketsupportedOptions {
    public static void main(String[] args) throws IOException {

        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;

        Socket socket = new Socket(addr, port);

        System.out.println(socket.supportedOptions());
        socket.close();
    }
}

Output:

[SO_SNDBUF, IP_TOS, SO_KEEPALIVE, SO_REUSEADDR, TCP_NODELAY, SO_RCVBUF, SO_LINGER]


Some other methods of Socket class

Socket()This method creates an unconnected Socket.

Socket(Proxy)This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of other settings.

Socket(InetAddress, int)This method creates a stream socket and connects it to the specified port number at the specified IP address.

Socket(String, int)This method creates a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress, int, InetAddress, int)This method creates a socket and connects it to the specified remote address on the specified remote port. The Socket will bind() to the local address and port supplied.

Socket(String, int, InetAddress, int)This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will bind() to the local address and port supplied.

bind(SocketAddress) This method binds the socket to a local address.

close()This method closes this socket.

connect(SocketAddress)This method connects this socket to the server.

connect(SocketAddress, int)This method connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout.

getChannel()This method returns the unique SocketChannelobject associated with this socket, if any.

getInetAddress()This method returns the address to which the socket is connected.

getInputStream()This method returns an input stream for this socket.

getKeepAlive()This method tests if SO_KEEPALIVE is enabled.

getLocalAddress()This method gets the local address to which the socket is bound.

getLocalPort()This method returns the local port number to which this socket is bound.

getLocalSocketAddress()This method returns the address of the endpoint this socket is bound to.

getOOBInline()This method tests if SO_OOBINLINE is enabled.

getOption(SocketOption)This method returns the value of a socket option.

getOutputStream()This method returns an output stream for this socket.

getPort()This method returns the remote port number to which this socket is connected.

getReceiveBufferSize()This method gets the value of the SO_RCVBUF option for this Socket, which is the buffer size used by the platform for input on this Socket.

getRemoteSocketAddress()This method returns the address of the endpoint this socket is connected to, or null if it is unconnected.

getReuseAddress()This method tests if SO_REUSEADDR is enabled.

getSendBufferSize()This method gets the value of the SO_SNDBUF option for this Socket, which is the buffer size used by the platform for output on this Socket.

getSoLinger()This method returns the setting for SO_LINGER.-1 returns implies that the option is disabled. The setting only affects socket closing.

getSoTimeout()This method returns setting for SO_TIMEOUT.0 returns implies that the option is disabled (i.e., timeout of infinity).

getTcpNoDelay()This method tests if TCP_NODELAY is enabled.

getTrafficClass()This method gets the traffic class or type of service in the IP header for packets sent from this Socket.

isBound()This method returns the binding state of the socket.

isClosed()This method returns the closed state of the socket.

isConnected()This method returns the connection state of the socket.

isInputShutdown()This method returns whether the read-half of the socket connection is closed.

isOutputShutdown()This method returns whether the write-half of the socket connection is closed.

sendUrgentData(int)This method sends one byte of urgent data to the socket. The byte to be sent is the lowest eight bits of the data parameter.

setKeepAlive(boolean)This method enables/disables SO_KEEPALIVE.

setOOBInline(boolean) This method enables/disables SO_OOBINLINE By default, this option is disabled, and TCP urgent data received on a socket is silently discarded.

setOption(SocketOption, Object)This method sets the value of a socket option.

setPerformancePreferences(int, int, int)This method sets performance preferences for this socket.

setReceiveBufferSize(int)This method sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

setReuseAddress(boolean)This method enables/disables the SO_REUSEADDR socket option.

setSendBufferSize(int)This method sets the SO_SNDBUF option to the specified value for this Socket. 

Socket.setSocketImplFactory(SocketImplFactory) This method sets the client socket implementation factory for the application. The factory can be specified only once.

setSoLinger(boolean, int)This method enables/disables SO_LINGER with the specified linger time in seconds.

setSoTimeout(int)This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds.

setTcpNoDelay(boolean)This method enables/disables TCP_NODELAY (disable/enable Nagle's algorithm).

setTrafficClass(int)This method sets the traffic class or type-of-service octet in the IP header for packets sent from this Socket.

shutdownInput()This method places the input stream for this socket at the "end of stream".

shutdownOutput()This method disables the output stream for this socket.

supportedOptions()This method returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

toString()This method converts this socket to a String.

Socket shutdownOutput() in Java

shutdownOutput(): This method is available in the java.net.Socket class of Java.

Syntax:

void java.net.Socket.shutdownOutput() throws IOException

This method disables the output stream for this socket.

For a TCP socket, any previously written data will be sent followed by TCP's normal connection termination sequence. 

Parameters: NA

Returns: NA

Throws:

1. IOException - if an I/O error occurs when shutting down this socket.

Approach

Java

package com.Socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class SocketshutdownOutput {
    public static void main(String[] args) throws IOException {

        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;

        Socket socket = new Socket(addr, port);

        socket.shutdownOutput();
        System.out.println("Successfully shutdownOutput");
        socket.close();
    }
}

Output:

Successfully shutdownOutput


Some other methods of Socket class

Socket()This method creates an unconnected Socket.

Socket(Proxy)This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of other settings.

Socket(InetAddress, int)This method creates a stream socket and connects it to the specified port number at the specified IP address.

Socket(String, int)This method creates a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress, int, InetAddress, int)This method creates a socket and connects it to the specified remote address on the specified remote port. The Socket will bind() to the local address and port supplied.

Socket(String, int, InetAddress, int)This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will bind() to the local address and port supplied.

bind(SocketAddress) This method binds the socket to a local address.

close()This method closes this socket.

connect(SocketAddress)This method connects this socket to the server.

connect(SocketAddress, int)This method connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout.

getChannel()This method returns the unique SocketChannelobject associated with this socket, if any.

getInetAddress()This method returns the address to which the socket is connected.

getInputStream()This method returns an input stream for this socket.

getKeepAlive()This method tests if SO_KEEPALIVE is enabled.

getLocalAddress()This method gets the local address to which the socket is bound.

getLocalPort()This method returns the local port number to which this socket is bound.

getLocalSocketAddress()This method returns the address of the endpoint this socket is bound to.

getOOBInline()This method tests if SO_OOBINLINE is enabled.

getOption(SocketOption)This method returns the value of a socket option.

getOutputStream()This method returns an output stream for this socket.

getPort()This method returns the remote port number to which this socket is connected.

getReceiveBufferSize()This method gets the value of the SO_RCVBUF option for this Socket, which is the buffer size used by the platform for input on this Socket.

getRemoteSocketAddress()This method returns the address of the endpoint this socket is connected to, or null if it is unconnected.

getReuseAddress()This method tests if SO_REUSEADDR is enabled.

getSendBufferSize()This method gets the value of the SO_SNDBUF option for this Socket, which is the buffer size used by the platform for output on this Socket.

getSoLinger()This method returns the setting for SO_LINGER.-1 returns implies that the option is disabled. The setting only affects socket closing.

getSoTimeout()This method returns setting for SO_TIMEOUT.0 returns implies that the option is disabled (i.e., timeout of infinity).

getTcpNoDelay()This method tests if TCP_NODELAY is enabled.

getTrafficClass()This method gets the traffic class or type of service in the IP header for packets sent from this Socket.

isBound()This method returns the binding state of the socket.

isClosed()This method returns the closed state of the socket.

isConnected()This method returns the connection state of the socket.

isInputShutdown()This method returns whether the read-half of the socket connection is closed.

isOutputShutdown()This method returns whether the write-half of the socket connection is closed.

sendUrgentData(int)This method sends one byte of urgent data to the socket. The byte to be sent is the lowest eight bits of the data parameter.

setKeepAlive(boolean)This method enables/disables SO_KEEPALIVE.

setOOBInline(boolean) This method enables/disables SO_OOBINLINE By default, this option is disabled, and TCP urgent data received on a socket is silently discarded.

setOption(SocketOption, Object)This method sets the value of a socket option.

setPerformancePreferences(int, int, int)This method sets performance preferences for this socket.

setReceiveBufferSize(int)This method sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

setReuseAddress(boolean)This method enables/disables the SO_REUSEADDR socket option.

setSendBufferSize(int)This method sets the SO_SNDBUF option to the specified value for this Socket. 

Socket.setSocketImplFactory(SocketImplFactory) This method sets the client socket implementation factory for the application. The factory can be specified only once.

setSoLinger(boolean, int)This method enables/disables SO_LINGER with the specified linger time in seconds.

setSoTimeout(int)This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds.

setTcpNoDelay(boolean)This method enables/disables TCP_NODELAY (disable/enable Nagle's algorithm).

setTrafficClass(int)This method sets the traffic class or type-of-service octet in the IP header for packets sent from this Socket.

shutdownInput()This method places the input stream for this socket at the "end of stream".

shutdownOutput()This method disables the output stream for this socket.

supportedOptions()This method returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

toString()This method converts this socket to a String.