Java Socket connect() method

connect(SocketAddress endpoint)

The connect() method of Java Socket class connects the specified socket to the server.

Syntax

Parameter

The parameter 'endpoint' represents the SocketAddress.

Return

NA

Throws

IOException - 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 1

Test it Now

Output:

Inet address: localhost/127.0.0.1
Port number: 1085

Example 2

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1085
	at java.net.InetSocketAddress.checkPort(InetSocketAddress.java:143)
	at java.net.InetSocketAddress.(InetSocketAddress.java:188)
	at com.javaTpoint.JavaSocketConnectExample2.main(JavaSocketConnectExample2.java:13)

Example 3

Test it Now

Output:

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.

Syntax

Parameter

endpoint - it represents the SocketAddress.

timeout ? it represents the timeout value to be used in milliseconds.

Return

NA

Throws

IOException - 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 1

Test it Now

Output:

Inet address: localhost/127.0.0.1
Port number: 1085

Example 2

Test it Now

Output:

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)




Latest Courses