//********* Non-blocking server *************************************** import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.net.InetSocketAddress; public class NBS { // NonBlockingServer public static void main(String[ ] args) throws Exception { // Store the message in a ByteBuffer for sending. String msg = "Hello, world!"; ByteBuffer buff = ByteBuffer.wrap(msg.getBytes()); // Open a non-blocking ServerSocketChannel. ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(port)); ssc.configureBlocking(false); // Await clients. while (true) { SocketChannel sc = ssc.accept(); // doesn't block if (sc == null) Thread.sleep(winks); // there's a better way else { buff.rewind(); // set position to 1st byte while (buff.hasRemaining()) sc.write(buff); // write the bytes sc.close(); // close the connection } } } private static final int port = 2233; private static final int winks = 2000; // 2 seconds }