Using a Selector to Manage Non-Blocking Server Sockets : NIO Socket « Network Protocol « Java

Using a Selector to Manage Non-Blocking Server Sockets


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 =;

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

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

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

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

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


Related examples in the same category

1.Non block server
2.Finger Server
3.Reading from a SocketChannel
4.Writing to a SocketChannel
5.Creating a Non-Blocking Server Socket
6.Creating a Non-Blocking Socket: requires a socket channel.
7.Accepting a Connection on a ServerSocketChannel