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

Java examples for Network:Socket Channel

Description

Using a Selector to Manage Non-Blocking 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.SocketChannel;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) throws Exception {
    Selector selector = null;/*from w ww .j a  va  2  s .co  m*/
    try {
      selector = Selector.open();

      SocketChannel sChannel1 = createSocketChannel("hostname.com", 80);
      SocketChannel sChannel2 = createSocketChannel("hostname.com", 80);

      sChannel1.register(selector, sChannel1.validOps());
      sChannel2.register(selector, sChannel1.validOps());
    } catch (IOException e) {
    }

    // Wait for events
    while (true) {
      try {
        // Wait for an event
        selector.select();
      } catch (IOException e) {
        // Handle error with selector
        break;
      }

      // Get list of selection keys with pending events
      Iterator it = selector.selectedKeys().iterator();

      // Process each key at a time
      while (it.hasNext()) {
        // Get the selection key
        SelectionKey selKey = (SelectionKey) it.next();

        it.remove();

        try {
          processSelectionKey(selKey);
        } catch (IOException e) {
          selKey.cancel();
        }
      }
    }
  }

  public static SocketChannel createSocketChannel(String hostName, int port)
      throws IOException {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);

    sChannel.connect(new InetSocketAddress(hostName, port));
    return sChannel;
  }

  public static void processSelectionKey(SelectionKey selKey)
      throws IOException {
    if (selKey.isValid() && selKey.isConnectable()) {
      SocketChannel sChannel = (SocketChannel) selKey.channel();

      boolean success = sChannel.finishConnect();
      if (!success) {
        // An error occurred; handle it

        // Unregister the channel with this selector
        selKey.cancel();
      }
    }
    if (selKey.isValid() && selKey.isReadable()) {
      // Get channel with bytes to read
      SocketChannel sChannel = (SocketChannel) selKey.channel();

      // See Reading from a SocketChannel
    }
    if (selKey.isValid() && selKey.isWritable()) {
      SocketChannel sChannel = (SocketChannel) selKey.channel();

    }
  }
}

Related Tutorials