Online Java Compiler By
JavaTpoint.com
import java.io.IOException; import java.net.*; public class JavaSocketExample1 { 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); //setSendBufferSize() sets the send buffer size or SO_SNDBUF option with the specified value socket.setSendBufferSize(67); //getSendBufferSize() method returns the buffer size(SO_SNDBUF) used by the platform for output System.out.println("Send Buffer size: "+socket.getSendBufferSize()); //enabling the boolean value true boolean on=false; //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 if(socket.getKeepAlive()){ System.out.println("SO_KEEPALIVE option is enabled"); } else{ System.out.println("SO_KEEPALIVE option is disabled"); } //getRemoteSocketAddress() returns the address of the endpoint of the specified socket if the socket is connected System.out.println("Remote socket address: "+socket.getRemoteSocketAddress()); } }
Output