集册 Java实例教程 使用选择器管理非

使用选择器管理非

欢马劈雪     最近更新时间:2020-01-02 10:19:05

494
使用选择器管理非阻塞套接字


import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.channels.SelectionKey;
/**
NowJava.com 提供 
**/

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;

    try {

      selector = Selector.open();


      SocketChannel sChannel1 = createSocketChannel("hostname.com", 80);
      /** from 
      N  o w  J a v a . c o m**/

      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


        
展开阅读全文