ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Introducing Nonblocking Sockets
Pages: 1, 2, 3

Client Nonblocking

To check if the developed server works properly in a nonblocking way, I will implement a client that continuously writes on the socket channel the string "Client XXX," where "XXX" in a number passed by the command line. For example, while this client is running with the number 89, the server console shows "Client 89 Client 89 Client 89 Client 89 ..." What will happen if another client starts with the number 92? If the server were blocking, nothing would happen; the server application would keep on showing a sequence of "Client 89" strings. Since our server uses nonblocking sockets, the console would show something like this: "Client 89 Client 89 Client 92 Client 89 Client 92 Client 92 Client 89 Client 89 ..." That means the read/write operations on the socket channel don't block the server application execution.



Here is a fragment of the client application code:

// Create client SocketChannel
SocketChannel client = SocketChannel.open();

// nonblocking I/O
client.configureBlocking(false);

// Connection to host port 8000
client.connect(new java.net.InetSocketAddress(host,8000));

// Create selector
Selector selector = Selector.open();

// Record to selector (OP_CONNECT type)
SelectionKey clientKey = client.register(selector, SelectionKey.OP_CONNECT);

// Waiting for the connection
while (selector.select(500)> 0) {

  // Get keys
  Set keys = selector.selectedKeys();
  Iterator i = keys.iterator();

  // For each key...
  while (i.hasNext()) {
    SelectionKey key = (SelectionKey)i.next();

    // Remove the current key
    i.remove();

    // Get the socket channel held by the key
    SocketChannel channel = (SocketChannel)key.channel();

    // Attempt a connection
    if (key.isConnectable()) {

      // Connection OK
      System.out.println("Server Found");

      // Close pendent connections
      if (channel.isConnectionPending())
        channel.finishConnect();

      // Write continuously on the buffer
      ByteBuffer buffer = null;
      for (;;) {
        buffer = 
          ByteBuffer.wrap(
            new String(" Client " + id + " ").getBytes());
        channel.write(buffer);
        buffer.clear();
      }

    }
  }
}

As you will note, the structure of the client application recalls the one you have seen for the server. However, there are some differences. The socket channel is associated to the selector by the option OP_CONNECT, which means the selector will have to inform the client when the server accepts the connection. For the client application, the loop is not infinite. The while condition is:

while (selector.select(500)> 0)

This means that the client attempts the connection for 500 milliseconds; if there's no answer, the select method will return 0 because the server is not active on the channel. Inside of the loop, the client checks if the key is connectable. In this case, the client closes the pending connections, if there are any, and then writes the string "Client" followed by the value of the id variable retrieved by the command line parameters.

Conclusion

The new Java 1.4 I/O system is a big step forward towards carrying out fast, flexible, and scalable Java applications. As shown in this article, by means of the nonblocking socket you can write a nonblocking socket-based application without dealing with threads manually.

Resources

D. Flanagan, "Top Ten Cool New Features of Java 2SE 1.4," O'Reilly Network, March 2002.

J. Zukowski, "New I/O Functionality for Java 2 Standard Edition 1.4," java.sun.com, December 2001.

T. Burns, "Nonblocking Socket I/O in JDK 1.4," Owl Mountain Software, December 2001.

A. Saltarin, "New I/O API in JDK 1.4," MokaByte N59, January 2002.

Giuseppe Naccarato has a degree in computer science and works as software developer for an IT company based in Glasgow (UK). His main interests are J2EE- and .Net-related technologies. Contact Giuseppe at http://www.giuseppe-naccarato.com.


Return to ONJava.com.