Online Java Compiler By
JavaTpoint.com
import java.io.DataOutputStream; import java.io.IOException; import java.net.*; public class JavaSocketExample4 { 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); //The isConnected() method returns the connected state for this socket System.out.println("The socket is connected: "+socket.isConnected()); //The isBound() states whether this socket is bounded or not System.out.println("The socket is binded: "+socket.isBound()); //The getLocalPort() method returns the port number for this socket. System.out.println("Local Port: "+socket.getLocalPort()); //getOutputStream() returns an output stream for writing bytes to this socket. DataOutputStream outputStream=new DataOutputStream(socket.getOutputStream()); System.out.println("Output Stream: "+outputStream); } }
Output