01: //********* Non-blocking server ***************************************
02: 
03: import java.nio.ByteBuffer;
04: import java.nio.channels.ServerSocketChannel;
05: import java.nio.channels.SocketChannel;
06: import java.net.InetSocketAddress;
07: 
08: public class NBS {  // NonBlockingServer
09:     public static void main(String[ ] args) throws Exception {
10:         // Store the message in a ByteBuffer for sending.
11:         String msg = "Hello, world!";
12:         ByteBuffer buff = ByteBuffer.wrap(msg.getBytes());
13:     
14:         // Open a non-blocking ServerSocketChannel.
15:         ServerSocketChannel ssc = ServerSocketChannel.open();
16:         ssc.socket().bind(new InetSocketAddress(port));
17:         ssc.configureBlocking(false);
18: 
19:         // Await clients.
20:         while (true) {
21:             SocketChannel sc = ssc.accept(); // doesn't block
22:             if (sc == null) 
23:                 Thread.sleep(winks); // there's a better way
24:             else {
25:                 buff.rewind();    // set position to 1st byte
26:                 while (buff.hasRemaining())
27:                   sc.write(buff); // write the bytes
28:                 sc.close();       // close the connection
29:             }
30:         }
31:     }
32:     private static final int port = 2233;
33:     private static final int winks = 2000; // 2 seconds
34: }