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.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);
          
        }
      }
    }
  }
}

   
  








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