Using a Selector to Manage Non-Blocking Server Sockets : ServerSocketChannel « Network « Java Tutorial






import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Main {
  public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));

    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
      selector.select();
      Iterator it = selector.selectedKeys().iterator();
      while (it.hasNext()) {
        SelectionKey selKey = (SelectionKey) it.next();
        it.remove();

        if (selKey.isAcceptable()) {
          ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
          SocketChannel sc = ssChannel.accept();
          ByteBuffer bb =ByteBuffer.allocate(100);
          sc.read(bb);
          
        }
      }
    }
  }
}








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