Test non-blocking accept() using ServerSocketChannel : ServerSocketChannel « Network « Java Tutorial






import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Test non-blocking accept() using ServerSocketChannel.
 */
public class MainClass {
  public static final String GREETING = "Hello I must be going.\r\n";

  public static void main(String[] argv) throws Exception {
    int port = 1234; // default

    ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
    ServerSocketChannel ssc = ServerSocketChannel.open();

    ssc.socket().bind(new InetSocketAddress(port));
    ssc.configureBlocking(false);

    while (true) {
      System.out.println("Waiting for connections");

      SocketChannel sc = ssc.accept();

      if (sc == null) {
        Thread.sleep(2000);
      } else {
        System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());

        buffer.rewind();
        sc.write(buffer);
        sc.close();
      }
    }
  }
}








19.15.ServerSocketChannel
19.15.1.ServerSocketChannel
19.15.2.New IO Hello Server
19.15.3.Test non-blocking accept() using ServerSocketChannel
19.15.4.Accepting a Connection on a ServerSocketChannel
19.15.5.Using a Selector to Manage Non-Blocking Server Sockets
19.15.6.Detecting When a Non-Blocking Socket Is Closed by the Remote Host