The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class has been associated exactly with 1 remote host, for connecting to another different host, we must create a new socket object.
The syntax for importing Socket class from java.net package :
import java.net.Socket;
Methods used in Socket class :
Method | Description |
---|---|
bind(SocketAddress bindpoint) | This method is used for binding a socket to a local address. |
Close() | This method is used for terminating a socket. |
connect(SocketAddress endpoint) | This method is used in connecting a socket to the server. |
getChannel() | This method returns out the object which is associated with the socket if any. |
getInetAddress() | This method returns the Address to which the socket is connected to. |
getInputStream() | This method returns the input stream for the socket. |
getKeepAlive() | This method is used to check if SO_KEEPALIVE is enabled or not. |
getLocalAddress() | This method is used to fetch the local address to which the socket is bound. |
getLocalPort() | This method returns the local address to which the socket is bound to. |
getLocalSocketAddress() | This method returns the endpoint for which the socket is bound. |
getOOBInline() | This method checks if SO_OOBINLINE is enabled. |
getOutputStream() | This method returns the output stream for the socket. |
getPort() | This method returns the remote port number with which the socket is associated to. |
getReceiveBufferSize() | This method is used to fetch the value of SO_RCVBUF option for the socket, which is a buffer size used as input by the platform on the socket. |
getRemoteSocketAddress() | This method returns, address of the endpoint for the socket or if it’s not connected then it returns null. |
getReuseAddress() | This method checks if REUSE_ADDR is enabled. |
getSendBufferSize() | This method is used to get the value of SO_SNDBUF option of the socket which is used as a buffer size for output by the platform on the socket. |
getSoLinger() | This method returns the setting for SO_LINGER |
getSoTimeout() | This method returns the setting for S0_TIMEOUT |
getTcpNoDelay() | This method is used for testing if TCP_NODELAY is enabled or not. |
getTrafficClass() | This method gets 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 data) | This method sends one byte of urgent data on the socket |
setKeepAlive(boolean on) | This method enables/disables SO_KEEPALIVE |
setOOBInline(boolean on) | This Method enables/disables SO_OOBINLINE (a receipt of TCP urgent data) By default, this option is disabled, and TCP urgent data received on a socket is silently discarded. |
setPerformancePreferences(int connectionTime, int latency, int bandwidth) | This method sets performance preferences for this socket. |
setReceiveBufferSize(int size) | This method sets the SO_RCVBUF option to the specified value for this Socket. |
setReuseAddress(boolean on | This method enables/disables the SO_REUSEADDR socket option |
setSendBufferSize(int size) | This method sets the SO_SNDBUF option to the specified value for this Socket |
setSocketImplFactory(SocketImplFactory fac | This method sets the client socket implementation factory for the application. |
setSoLinger(boolean on, int linger) | This method enables/disables SO_LINGER with the specified linger time in seconds. |
setSoTimeout(int timeout) | This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds. |
setTcpNoDelay(boolean on | This method enables/disables TCP_NODELAY (disable/enable Nagle’s algorithm). |
setTrafficClass(int tc) | This method sets 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”. |
toString() | This method converts the Socket to a string. |
Applications of Socket Class:
1. Socket class is implemented in creating a stream socket and which is connected to a specified port number and port address.
public Socket(InetAddress address, int port)
2. Socket class is used for the creation of socket and connecting to the specified remote address on the specified remote port in javax.net
SocketFactory.createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
3. In javax.ssl.net, the Socket class is used to return a socket layered over an existing socket connected to the named host at a given port.
SSLSocketFactory.createSocket(Socket s, String host, int port, boolean autoClose)
4. In javax.rmi.ssl, Socket class is used for creating an SSL socket.
SslRMIClientSocketFactory.createSocket(String host, int port)
5. In java.nio.channels, Socket class is used for retrieving a socket associated with its channel
SocketChannel.socket()
Java Example for Socket class Implementation :
1. For Server Side:
Java
import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket( 6666 ); // establishes connection Socket soc = ss.accept(); // invoking input stream DataInputStream dis = new DataInputStream(ss.getInputStream()); String str = (String)dis.readUTF(); System.out.println( "message= " + str); // closing socket ss.close(); } // for catching Exception in run time catch (Exception e) { System.out.println(e); } } } |
Output on Client :
2. For Client Side :
Java
import java.io.*; import java.net.*; public class MyClient { public static void main(String[] args) { try { // initializing Socket Socket soc = new Socket( "localhost" , 6666 ); DataOutputStream d = new DataOutputStream( soc.getOutputStream()); // message to display d.writeUTF( "Hello GFG Readers!" ); d.flush(); // closing DataOutputStream d.close(); // closing socket soc.close(); } // to initialize Exception in run time catch (Exception e) { System.out.println(e); } } } |
Output on server :