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) { }

Comments

20 Jan 2010 - 1:27pm by kR105 (not verified)

Thank you!! Your examples helped me a lot!

3 Feb 2010 - 5:11am by Anonymous (not verified)

Thanks, found this very helpfull!

21 Mar 2010 - 4:18am by Kranach (not verified)

thanks for examples on network nio, helped a lot!

13 Jul 2010 - 8:10pm by Andi (not verified)

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?

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.