Using a Selector to Manage Non-Blocking Server Sockets - Java Network

Java examples for Network:Socket Channel

Description

Using a Selector to Manage Non-Blocking Server Sockets

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

public class Main {
  public void m() throws Exception {
    try {/*from ww w . j av a  2s . c  om*/
      Selector selector = Selector.open();

      // Create two non-blocking server sockets on 80 and 81
      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));

      // Register both channels with selector
      ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
      ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

      while (true) {
        selector.select();
        Iterator it = selector.selectedKeys().iterator();
        // Process each key
        while (it.hasNext()) {
          // Get the selection key
          SelectionKey selKey = (SelectionKey) it.next();

          // Remove it from the list to indicate that it is being processed
          it.remove();

          // Check if it's a connection request
          if (selKey.isAcceptable()) {
            // Get channel with connection request
            ServerSocketChannel ssChannel = (ServerSocketChannel) selKey
                .channel();
          }
        }
      }
    } catch (IOException e) {
    }
  }
}

Related Tutorials