<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    狂奔 lion

    自強(qiáng)不息

    NIO學(xué)習(xí)之Web服務(wù)器示例

    1 根據(jù)cpu core數(shù)量確定selector數(shù)量
    2 用一個(gè)selector服務(wù)accept,其他selector按照core-1分配線程數(shù)運(yùn)行
    3 accept selector作為生產(chǎn)者把獲得的請(qǐng)求放入隊(duì)列
    4 某個(gè)selector作為消費(fèi)者從blocking queue中取出請(qǐng)求socket channel,并向自己注冊(cè)
    5 當(dāng)獲得read信號(hào)時(shí),selector建立工作任務(wù)線程worker,并提交給系統(tǒng)線程池
    6 worker線程排隊(duì)后在線程池中執(zhí)行,把協(xié)議頭讀入緩沖區(qū),然后解析,處理,響應(yīng),關(guān)閉連接

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.ClosedChannelException;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.LinkedBlockingQueue;

    public class NioServer {
        
    private static NioServer svr = new NioServer();
        
    private final int numProcessors = Runtime.getRuntime().availableProcessors();
        
    private static LinkedBlockingQueue<SocketChannel> queue = new LinkedBlockingQueue<SocketChannel>();
        
    private static ExecutorService es = Executors.newFixedThreadPool(3);
        
        
    private NioServer(){}
        
        
    public static NioServer getInstance(){return svr;}
        
        
    public void init(){
            
    try {
                
    for(int i=0;i<numProcessors - 1;i++){
                    Thread tk 
    = new Thread(new Talker());
                    tk.start();
                }

                
                Selector acceptSelector 
    = Selector.open();

                ServerSocketChannel ssc 
    = ServerSocketChannel.open();
                ssc.configureBlocking(
    false);

                InetSocketAddress isa 
    = new InetSocketAddress("127.0.0.1"8080);
                ssc.socket().bind(isa);

                ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);

                
    while (acceptSelector.select() > 0{
                    Set
    <SelectionKey> readyKeys = acceptSelector.selectedKeys();
                    Iterator
    <SelectionKey> i = readyKeys.iterator();

                    
    while (i.hasNext()) {
                        SelectionKey sk 
    = i.next();
                        i.remove();
                        
    if (sk.isAcceptable()) {
                            ServerSocketChannel nextReady 
    = (ServerSocketChannel) sk
                                    .channel();
                            SocketChannel s 
    = nextReady.accept();
                            s.configureBlocking(
    false);
                            queue.offer(s);
                        }

                    }

                }

            }
     catch (Exception e) {
                e.printStackTrace();
            }

        }

        
        
    private static class Talker implements Runnable{
            
    private Selector se = null;

            
            
    public Talker(){
                
    try {
                    
    this.se = Selector.open();
                }
     catch (IOException e) {
                    e.printStackTrace();
                }

            }

            
            
    public void addChannelIfAvailable(){
                
    try {
                    
    if(queue.isEmpty())
                        
    return;
                    SocketChannel sc 
    = queue.poll();
                    sc.register(se, SelectionKey.OP_READ);
                }
     catch (ClosedChannelException e) {
                    e.printStackTrace();
                }

            }

            
            
    public void run() {
                
    try {
                    
    while (true{
                        
    int skOps = se.select(20);
                        addChannelIfAvailable();
                        
    if(skOps <= 0){
                            
    continue;
                        }

                        
                        Set
    <SelectionKey> readyKeys = se.selectedKeys();
                        Iterator
    <SelectionKey> i = readyKeys.iterator();
                        
    while (i.hasNext()) {
                            SelectionKey sk 
    = i.next();
                            i.remove();
                            
                            
    if (sk.isValid() && sk.isReadable()) {
                                SocketChannel sc 
    = (SocketChannel) sk.channel();
                                sc.configureBlocking(
    false);
                                
                                Worker worker 
    = new Worker(sc);
                                es.execute(worker);    
                            }

                        }

                        Thread.sleep(
    300);
                    }

                }
     catch (IOException e) {
                    e.printStackTrace();
                }
     catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }

        
        
    private static class Worker implements Runnable{
            ByteBuffer bb 
    = ByteBuffer.allocateDirect(1024);
            SocketChannel sc 
    = null;
            
            
    public Worker(SocketChannel sc){
                Thread.currentThread().setName(
    this.toString());
                
    this.sc = sc;
            }

            
            
    public void run() {
                
    try {
                    
    try{
                        sc.read(bb);
                    }
    catch(IOException e){
                        e.printStackTrace();
                        sc.finishConnect();
                        sc.close();
                        
    return;
                    }

                    bb.flip();
                    
    byte[] bs = new byte[bb.limit()];
                    bb.get(bs);
                    bb.clear();
                    
                    StringBuilder sb 
    = new StringBuilder();
                    sb.append(
    "HTTP/1.1 200 OK").append("\n").append("Date:" + new Date()).append("\n");
                    sb.append(
    "Server:NIO Server By Yi Yang\n\n");
                    bb.put(sb.toString().getBytes());
                    
                    bb.flip();
                    sc.write(bb);
                    bb.clear();
                    
                    FileInputStream is 
    = new FileInputStream("E:/test.html");
                    is.getChannel().transferTo(
    01024, sc);
                    
                    is.close();
                    sc.finishConnect();
                    sc.close();
                }
     catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

        
        
    public static void main(String[] args) throws Exception {
            NioServer server 
    = NioServer.getInstance();
            server.init();
        }

    }
    ===============06/27/10 
    如何解析header?,以行為單位讀取,按照header敏感的關(guān)鍵字進(jìn)行匹配 對(duì)于首行取得對(duì)方調(diào)用的方法GET/POST 地址 和協(xié)議版本 
    然后根據(jù)用戶的配置,和解析地址請(qǐng)求,獲得響應(yīng)的servlet,并把通過反射+默認(rèn)構(gòu)造函數(shù)構(gòu)造這個(gè)servlet,解析地址參數(shù)等設(shè)置到對(duì)象httpservletrequest和httpservletresponse中,然后通過反射invoke對(duì)應(yīng)的get/post/put/delete等方法,并把封裝的兩個(gè)對(duì)象作為參數(shù)傳進(jìn)去,同時(shí)在response的header中傳遞一個(gè)cookie作為session的依據(jù)。


     @2008 楊一. 版權(quán)所有. 保留所有權(quán)利

    posted on 2010-06-25 19:19 楊一 閱讀(1967) 評(píng)論(0)  編輯  收藏 所屬分類: Java SE

    <2010年6月>
    303112345
    6789101112
    13141516171819
    20212223242526
    27282930123
    45678910

    導(dǎo)航

    公告

    本人在blogjava上發(fā)表的文章及隨筆除特別聲明外均為原創(chuàng)或翻譯,作品受知識(shí)產(chǎn)權(quán)法保護(hù)并被授權(quán)遵從 知識(shí)分享協(xié)議:署名-非商業(yè)性使用-相同方式共享 歡迎轉(zhuǎn)載,請(qǐng)?jiān)谵D(zhuǎn)載時(shí)注明作者姓名(楊一)及出處(m.tkk7.com/yangyi)
    /////////////////////////////////////////
    我的訪問者

    常用鏈接

    留言簿(5)

    隨筆分類(55)

    隨筆檔案(55)

    相冊(cè)

    Java

    其他技術(shù)

    生活

    最新隨筆

    搜索

    積分與排名

    最新評(píng)論

    閱讀排行榜

    評(píng)論排行榜

    自強(qiáng)不息


    用心 - 珍惜時(shí)間,勇于創(chuàng)造
    主站蜘蛛池模板: 国产亚洲精品欧洲在线观看| 亚洲人成影院在线无码按摩店| 在线观看人成网站深夜免费| 1000部免费啪啪十八未年禁止观看| 免费国产黄网站在线观看视频| 外国成人网在线观看免费视频| 久久青草精品38国产免费| 特级做A爰片毛片免费看无码| 两个人看的www免费高清| 鲁丝片一区二区三区免费| 国产成人精品无码免费看| 日韩内射激情视频在线播放免费| 久久99精品视免费看| 国产成人精品免费视频大全麻豆| 中文字幕无码播放免费| 日美韩电影免费看| 亚洲成人高清在线| 亚洲色欲久久久综合网| 亚洲欧洲日产国码久在线观看| 久久亚洲AV无码精品色午夜 | 99爱在线精品视频免费观看9| 久久久久免费看成人影片| 国产免费不卡v片在线观看| 黄a大片av永久免费| 亚洲最大av无码网址| 国产成人亚洲精品青草天美| 亚洲美女视频免费| 亚洲中文无码永久免| 免费激情网站国产高清第一页| 国产在线精品观看免费观看| 最近2022中文字幕免费视频 | 国产精品免费观看视频| 免费人成毛片动漫在线播放| 成年人网站免费视频| 国产成人免费福利网站| 亚洲精品无码成人AAA片| 亚洲冬月枫中文字幕在线看 | 亚洲人成网址在线观看| 中文字幕在线观看亚洲日韩| 日韩在线视频播放免费视频完整版| 免费无码av片在线观看|