Online Java Compiler By
JavaTpoint.com
import java.io.IOException; import java.net.*; public class JavaSocketExample2 { public static void main(String[] args) throws IOException { Socket socket = new Socket(); InetAddress inetAddress=InetAddress.getByName("localhost"); //the port should be greater or equal to 0, else it will throw an error int port=1085; //calling the constructor of the SocketAddress class SocketAddress socketAddress=new InetSocketAddress(inetAddress, port); //binding the socket with the inetAddress and port number socket.bind(socketAddress); //connect() method connects the specified socket to the server socket.connect(socketAddress); //enabling the SO_LINGER option boolean on=true; //setting the integer value for timeout int timeout=90; socket.setSoLinger(on,timeout); //getSoLinger() method returns the setting if the SO_Linger option is set System.out.println("Send Buffer size: "+socket.getSoLinger()); //integer timeout value socket.setSoTimeout(timeout); //getSoTimeout() method returns the setting for SO_TIMEOUT option System.out.println("Timeout value: "+socket.getSoTimeout()); //setTcpNoDelay() method enables or disables the SO_TIMEOUT option socket.setTcpNoDelay(on); //getTcpNoDelay() returns the setting for SO_TIMEOUT option System.out.println("SO_TIMEOUT option is enabled: "+socket.getTcpNoDelay()); //setKeepAlive() method either enables or disables the SO_KEEPALIVE option socket.setKeepAlive(on); //getKeepAlive() returns a boolean indicating whether SO_KEEPALIVE option is enabled or not System.out.println("SO_KEEPALIVE is enabled: "+socket.getKeepAlive()); //getLocalSocketAddress() returns the address of the endpoint to which this socket is bound System.out.println("Local socket address: "+socket.getLocalSocketAddress()); } }
Output