NIO應用

NIO:

1,爲所有的原始類型提供buffer緩存支持。

2,字符集編碼解碼解決方案。

3,channel 一個新的IO對象。

4,支持鎖和內存映射文件的文件訪問接口。

5,提供多路非阻塞式的高伸縮性網絡IO

package thread;

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.Set;

public class NIO {
    int[] port;
    private void execute() throws IOException{
        //創建一個新的選擇器
        Selector selector = Selector.open();
        //打開每個端口的監聽,並向給定的選擇器註冊此通道接收客戶端連接的IO事件
        for(int i =0 ;i<port.length;i++){
            //打開服務器套接字通道
            ServerSocketChannel ssc = ServerSocketChannel.open();
            //設置此通道爲非阻塞式
            ssc.configureBlocking(false);
            //綁定到特定地址
            ServerSocket ss = ssc.socket();
            InetSocketAddress add = new InetSocketAddress(port[i]);
            ss.bind(add);
            //向給定的選擇器註冊此通道的連接事件
            ssc.register(selector,SelectionKey.OP_ACCEPT);
            System.out.println(port[i]);
        }
        while(true){
            //這個方法會阻塞,直到至少有一個已註冊的事件發生。當一個或者更多的事件發生時,此方法將返回所發生的事件的數量。
            int num = selector.select();
            //迭代所有選擇鍵,以處理特定的IO事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iter = selectionKeys.iterator();
            SocketChannel sc;
            while(iter.hasNext()){
                SelectionKey key = iter.next();
                if((key.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT){
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    sc = ssc.accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                    iter.remove();
                }else if((key.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ){
                    sc = (SocketChannel) key.channel();
                    int byteEchoed = 0;
                    ByteBuffer echoBuffer = ByteBuffer.allocate(1024);
                    while(true){
                        echoBuffer.clear();
                        int r = sc.read(echoBuffer);
                        if(r == -1){break;}
                        echoBuffer.flip();
                        sc.write(echoBuffer);
                        byteEchoed+=r;
                    }
                    iter.remove();
                }
                
            }
            
        }
        
        
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章