Java NIO 非堵塞效劳器例如姓名:邓以克 网名:phinecos(洞庭散人) MSN: phinecos@msn 出处: ://phinecos blogs /本文版权归作者所有,欢迎传阅,但请保存此段声明。 以前一直用的是“ervery thread per connection〞的效劳器端模式,今日试了下NIO 非堵塞模式的效劳器。 不过 java 不能实现 I/O 完成端口模型,这点很遗憾package com.vista.Server;import java.io.IOException;import java.net.InetSocketAddress;import java.net.ServerSocket;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;import java.util.LinkedList;import java.util.Set;public class SelectorServer { private static int DEFAULT_SERVERPORT = 6018;//默认端口 private static int DEFAULT_BUFFERSIZE = 1024;//默认缓冲区大小为 1024字节 private ServerSocketChannel channel; private LinkedList clients; private Selector readSelector; private ByteBuffer buffer;//字节缓冲区 private int port; public SelectorServer(int port) throws IOException { this.port = port; this.clients = new LinkedList(); this.channel = null; this.readSelector = Selector.open();//翻开选择器 this.buffer = ByteBuffer.allocate(DEFAULT_BUFFERSIZE); } // 效劳器程序在效劳循环中调用 sericeClients()方法为已接受的客户效劳 public void serviceClients()throws IOException { Set keys; Iterator it; SelectionKey key; SocketChannel client; // 在 readSelector 上调用 select()方法,参数 1 代表假如调用 select 的时候 那么堵塞最多 1 秒钟等待可用的客户端连接 if(readSelector.select(1) > 0) { keys = readSelector.selectedKeys(); // 取得代表端通道的键集合 it = keys.iterator(); // 遍历,为每一个客户效劳 while(it.hasNext()) { key = (SelectionKey)it.next(); if(key.isReadable()) { // 假如通道可读,那么读此通道到 buffer 中 int bytes; client = (SocketChannel)key.channel();// ...