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

使用选择器管理非

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

367
使用选择器管理非阻塞服务器套接字
//时代Java - nowjava.com

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 {

      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//from N o  w  J a v a . c o m - 时  代  Java

      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();


          
展开阅读全文