Java Socket close() method

The close() method of Java Socket class closes the specified socket. Once the socket has been closed, it is not available for further networking use. If the socket has a channel, the channel is also closed.

Syntax

Parameter

NA

Return

NA

Specified by

  • The close() method in interface AutoCloseable
  • The close() method in interface Closeable

Throws

IOException - if an I/O error occurs when closing this socket.

Example 1

Test it Now

Output:

Inet address: localhost/127.0.0.1
Port number: 1085
After calling the close() method...
Inet address: localhost/127.0.0.1
Port number: 1085

Example 2

Test it Now

Output:

Exception in thread "main" java.net.SocketException: Socket is closed
	at java.net.Socket.bind(Socket.java:625)
	at com.javaTpoint.JavaSocketCloseExample2.main(JavaSocketCloseExample2.java:17)




Latest Courses