Java Socket connect() methodconnect(SocketAddress endpoint)The connect() method of Java Socket class connects the specified socket to the server. SyntaxParameterThe parameter 'endpoint' represents the SocketAddress. ReturnNA ThrowsIOException - if an error occurs during the connection. IllegalBlockingModeException - if this socket has an associated channel and the channel is in non-blocking mode. IllegalArgumentException - if the specified endpoint is null or if the SocketAddress subclass not supported by this socket. Example 1Test it NowOutput: Inet address: localhost/127.0.0.1 Port number: 1085 Example 2Test it NowOutput: Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1085 at java.net.InetSocketAddress.checkPort(InetSocketAddress.java:143) at java.net.InetSocketAddress. Example 3Test it NowOutput: Exception in thread "main" java.lang.IllegalArgumentException: connect: The address can't be null at java.net.Socket.connect(Socket.java:560) at java.net.Socket.connect(Socket.java:538) at com.javaTpoint.JavaSocketConnectExample3.main(JavaSocketConnectExample3.java:13) connect(SocketAddress endpoint, int timeout)The connect() method of Java Socket class connects this socket to the server with the given timeout value. A zero timeout is inferred as an infinite timeout. SyntaxParameterendpoint - it represents the SocketAddress. timeout ? it represents the timeout value to be used in milliseconds. ReturnNA ThrowsIOException - if an error occurs during the connection. SocketTimeoutException - if timeout expires before connecting. IllegalBlockingModeException - if this socket has an associated channel and the channel is in non-blocking mode. IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket. Example 1Test it NowOutput: Inet address: localhost/127.0.0.1 Port number: 1085 Example 2Test it NowOutput: Exception in thread "main" java.lang.IllegalArgumentException: connect: timeout can't be negative at java.net.Socket.connect(Socket.java:563) at com.javaTpoint.JavaSocketConnectExample5.main(JavaSocketConnectExample5.java:19) Next TopicJava Socket Class |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India