Creating a Non-Blocking Socket
This example shows how to create a non-blocking socket. A
non-blocking socket requires a socket channel.
See also Using a Selector to Manage Non-Blocking Sockets.
// Creates a non-blocking socket channel for the specified host name and port.
// connect() is called on the new channel before it is returned.
public static SocketChannel createSocketChannel(String hostName, int port) throws IOException {
// Create a non-blocking socket channel
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
// Send a connection request to the server; this method is non-blocking
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}
// Create a non-blocking socket and check for connections
try {
// Create a non-blocking socket channel on port 80
SocketChannel sChannel = createSocketChannel("hostname.com", 80);
// Before the socket is usable, the connection must be completed
// by calling finishConnect(), which is non-blocking
while (!sChannel.finishConnect()) {
// Do something else
}
// Socket channel is now ready to use
} catch (IOException e) {
}
Thank you!! Your examples helped me a lot!
Thanks, found this very helpfull!
thanks for examples on network nio, helped a lot!
Hi there, thanks for the good examples. One big lurking issue (strangely enough, never addressed by authors) is that the call "new InetSocketAddress(hostName, port)" is blocking, making the whole process ... blocking. What's sad is that nio doesn't seem to provide a way to resolve a host name in a non-blocking fashion. Or am I missing something?