01: //********* Non-blocking client ***************************************
02: import java.nio.ByteBuffer;
03: import java.nio.channels.SocketChannel;
04: import java.net.InetSocketAddress;
05: 
06: public class NBC {  // NonBlockingClient
07:     public static void main(String[ ] args) throws Exception {
08:         if (args.length < 1) {
09:           System.err.println("Usage: NBC <server's addr>");
10:           return;
11:         }
12:         // Create a ByteBuffer to receive data.
13:         ByteBuffer buff = ByteBuffer.allocate(buff_size);
14: 
15:         // Open a socket channel and configure it as blocking.
16:         SocketChannel sc = SocketChannel.open();
17:         sc.configureBlocking(false);
18: 
19:         // Attempt to connect: as blocking is off, the connect
20:         // call returns at once
21:         sc.connect(new InetSocketAddress(args[0], port));
22:         
23:         // Now wait until the connection is finished.
24:         // (There's a better way.)
25:         while (!sc.finishConnect())
26:             Thread.sleep(500);      
27:     
28:         // Read from the channel when data are available.
29:         // (There's a better way.)
30:         while (sc.read(buff) != -1) // -1 marks end of stream
31:             Thread.sleep(500);
32:         sc.close();
33:         System.out.println(new String(buff.array()));
34:     }
35:     private static final int port = 2233;
36:     private static final int buff_size = 512; // in bytes
37: }