When you connect to a socket, the current thread blocks until the connection has been established or a timeout has elapsed. Similarly, when you read or write data through a socket, the current thread blocks until the operation is successful or has timed out.
In interactive applications, you would like to give users an option to simply cancel a socket connection that does not appear to produce results. However, if a thread blocks on an unresponsive socket, you cannot unblock it by calling
To interrupt a socket operation, use a
SocketChannel, a feature of the
java.nio package. Open the
SocketChannel like this:
SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));
A channel does not ...