1 import java.io.IOException; 2 import java.net.InetSocketAddress; 3 import java.nio.channels.SelectionKey; 4 import java.nio.channels.Selector; 5 import java.nio.channels.ServerSocketChannel; 6 import java.util.Iterator; 7 8 public class TCPServerSelector{ 9 //緩衝區的長度 10 private static final int BUFSIZE = 256; 11 //select方法等待信道準備好的最長時間 12 private static final int TIMEOUT = 3000; 13 public static void main(String[] args) throws IOException { 14 if (args.length < 1){ 15 throw new IllegalArgumentException("Parameter(s): <Port> ..."); 16 } 17 //建立一個選擇器 18 Selector selector = Selector.open(); 19 for (String arg : args){ 20 //實例化一個信道 21 ServerSocketChannel listnChannel = ServerSocketChannel.open(); 22 //將該信道綁定到指定端口 23 listnChannel.socket().bind(new InetSocketAddress(Integer.parseInt(arg))); 24 //配置信道爲非阻塞模式 25 listnChannel.configureBlocking(false); 26 //將選擇器註冊到各個信道 27 listnChannel.register(selector, SelectionKey.OP_ACCEPT); 28 } 29 //建立一個實現了協議接口的對象 30 TCPProtocol protocol = new EchoSelectorProtocol(BUFSIZE); 31 //不斷輪詢select方法,獲取準備好的信道所關聯的Key集 32 while (true){ 33 //一直等待,直至有信道準備好了I/O操做 34 if (selector.select(TIMEOUT) == 0){ 35 //在等待信道準備的同時,也能夠異步地執行其餘任務, 36 //這裏只是簡單地打印"." 37 System.out.print("."); 38 continue; 39 } 40 //獲取準備好的信道所關聯的Key集合的iterator實例 41 Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); 42 //循環取得集合中的每一個鍵值 43 while (keyIter.hasNext()){ 44 SelectionKey key = keyIter.next(); 45 //若是服務端信道感興趣的I/O操做爲accept 46 if (key.isAcceptable()){ 47 protocol.handleAccept(key); 48 } 49 //若是客戶端信道感興趣的I/O操做爲read 50 if (key.isReadable()){ 51 protocol.handleRead(key); 52 } 53 //若是該鍵值有效,而且其對應的客戶端信道感興趣的I/O操做爲write 54 if (key.isValid() && key.isWritable()) { 55 protocol.handleWrite(key); 56 } 57 //這裏須要手動從鍵集中移除當前的key 58 keyIter.remove(); 59 } 60 } 61 } 62 }
1 public static void main(String[] args) throws IOException { 2 3 AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(0000)); 4 server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() { 5 final ByteBuffer buffer = ByteBuffer.allocate(1024); 6 7 @Override 8 public void completed(AsynchronousSocketChannel result, Object attachment) { 9 System.out.println(Thread.currentThread().getName()); 10 Future<Integer> writeResult = null; 11 try { 12 buffer.clear(); 13 result.read(buffer).get(100, TimeUnit.SECONDS); 14 buffer.flip(); 15 writeResult = result.write(buffer); 16 } catch (InterruptedException | ExecutionException e) { 17 e.printStackTrace(); 18 } catch (TimeoutException e) { 19 e.printStackTrace(); 20 } finally { 21 try { 22 server.accept(null, this); 23 writeResult.get(); 24 result.close(); 25 } catch (Exception e) { 26 System.out.println(e.toString()); 27 } 28 } 29 } 30 31 @Override 32 public void failed(Throwable exc, Object attachment) { 33 System.out.println("failed: " + exc); 34 } 35 }); 36 37 }