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?

17 May 2011 - 5:43am by shudong (not verified)

Andi,

Think you can use this API, which is non-blocking
public static InetSocketAddress createUnresolved(String host,int port).

17 Sep 2011 - 8:22pm by Kurt (not verified)

Instead of waiting for the connection the way you do, couldn't you first configure as blocking, and then change to non-blocking:
[code]
...
// Create a blocking socket channel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
// Kick off connection establishment
try {
socketOpenSuccessful = socketChannel.connect(new InetSocketAddress(this.hostAddress, this.socketPort));
} catch (IOException iOException) {
logger.log(Level.SEVERE, "Couldn''t get I/O for the connection to: {0}. {1}", new Object[]{socketIPAddress, iOException.toString()});
}
if (socketOpenSuccessful) {
socketChannel.configureBlocking(false);
int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
SelectionKey key = socketChannel.register(selector, interestSet);
...
[/code]

7 Apr 2012 - 6:15am by rahul (not verified)

I keep this as a portable set. Its got ynreethivg I need in a pinch except allen keys, but a cheap allen key set remedied that. The extensions are just long enough to reach any bolt I needed to get to. There are 2 different cases in the photos. The stock photo with the sockets in the lid is what I have and its a smaller case. Walmart sell the version with no sockets in the top lid. Same set, different case. Home Depot sells the same set under the Husky brand name (its the smaller case version) It can me a little difficult to remove some of the sockets but I rather have that then them falling out. (the bigger case had sockets that were a little easier to remove) From my experience, these are about the quality of craftsman from 10 years ago, slightly less quality than craftsman of 20 years ago, and eons better than the crap craftsman has been selling lately.

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.