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

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

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

    隨筆-23  評論-58  文章-0  trackbacks-0
    Reactor 模式的 JAVA NIO 多線程服務器,這是比較完善的一版了。Java 的 NIO 網(wǎng)絡模型實在是不好用,還是使用現(xiàn)成的好。
    public class NIOServer implements Runnable 
    {
        
    private static final Log log = LogFactory.getLog(NIOServer.class);

        
    private ExecutorService executor=null;
        
    private final Selector sel;
        
    private final ServerSocketChannel ssc;
        
    private HandleUtil ho;
        
        
    public NIOServer(int portnumber,HandleUtil ho) throws IOException
        
    {
            
    this.ho=ho;
            sel 
    = Selector.open();
            ssc 
    = ServerSocketChannel.open();
            ssc.socket().bind(
    new InetSocketAddress(portnumber));
            ssc.configureBlocking(
    false);
            ssc.register(sel,SelectionKey.OP_ACCEPT,
    new Acceptor());
        }

        
        
    public NIOServer(int portnumber,HandleUtil ho,ExecutorService executor) throws IOException
        
    {
            
    this.ho=ho;
            
    this.executor=executor;
            sel 
    = Selector.open();
            ssc 
    = ServerSocketChannel.open();
            ssc.socket().bind(
    new InetSocketAddress(portnumber));
            ssc.configureBlocking(
    false);
            ssc.register(sel,SelectionKey.OP_ACCEPT,
    new Acceptor());
        }

        
        @Override
        
    public void run()
        
    {
            
    try
            
    {
                
    while(sel.isOpen())
                
    {
                    
    int nKeys=sel.select(100);
                    
    if(nKeys==0)
                        Thread.sleep(
    100);
                    
    else if(nKeys>0)
                    
    {
                        Iterator
    <SelectionKey> it = sel.selectedKeys().iterator();
                        
    while (it.hasNext()) 
                        
    {
                            SelectionKey sk 
    = it.next();
                            it.remove();
                            
    if(sk.isAcceptable()||sk.isReadable()||sk.isWritable())
                            
    {
                                Runnable r 
    = (Runnable)sk.attachment();
                                r.run();
                            }

                        }

                    }

                }

            }

            
    catch(IOException | InterruptedException e)        { log.info(ExceptionUtil.getExceptionMessage(e));    }
        }

        
        
    class Acceptor implements Runnable 
        
    {
            @Override
            
    public void run() 
            
    {
                
    try
                
    {
                    SocketChannel sc 
    = ssc.accept();
                    
    if (sc != null)
                    
    {
                        sc.configureBlocking(
    false);
                        sc.socket().setTcpNoDelay(
    true);
                        sc.socket().setSoLinger(
    false-1);
                        SelectionKey sk
    =sc.register(sel, SelectionKey.OP_READ);
                        sk.attach(
    new Reader(sk));
                        sel.wakeup();
                    }

                }

                
    catch(IOException e) { log.info(ExceptionUtil.getExceptionMessage(e)); }
            }

        }

        
        
    class Reader implements Runnable 
        
    {
            
    private byte[] bytes=new byte[0];
            
    private SelectionKey sk;
            
            
    public Reader(SelectionKey sk)
            
    {
                
    this.sk=sk;
            }

            
            @Override
            
    public void run()
            
    {
                
    try
                
    {
                    SocketChannel sc 
    = (SocketChannel) sk.channel();
                    Handle handle
    =null;
                    
    if(ho.getParameterTypes()==null)
                        handle
    =(Handle)HandleUtil.getObjectByClassName(ho.getClassname());
                    
    else
                        handle
    =(Handle)HandleUtil.getObjectByClassName(ho.getClassname(), ho.getParameterTypes(), ho.getParameters());
                    handle.setSocketChannel(sc);
                    ByteBuffer buffer
    =ByteBuffer.allocate(1024);
                    
    int len=-1;
                    
    while(sc.isConnected() && (len=sc.read(buffer))>0)
                    
    {
                        buffer.flip();
                          
    byte [] content = new byte[buffer.limit()];
                        buffer.get(content);
                        bytes
    =StringUtil.arrayCoalition(bytes,content);
                        buffer.clear();
                    }

                    
    if(len==0)
                    
    {
                        
    if(executor==null)
                        
    {
                            
    byte[] bb=handle.execute(bytes);
                            sk.interestOps(SelectionKey.OP_WRITE);
                            sk.attach(
    new Writer(sk,ByteBuffer.wrap(bb)));
                            sk.selector().wakeup();
                        }

                        
    else
                        
    {
                            handle.setData(bytes);
                            Future
    <byte[]> future=executor.submit(handle);
                            sk.interestOps(SelectionKey.OP_WRITE);
                            sk.attach(
    new Writer(sk,future));
                            sk.selector().wakeup();
                        }

                    }

                    
    else if(len==-1)
                    
    {
                        sk.cancel();
                        sk.selector().selectNow();
                        sc.close();
                    }

                }

                
    catch(Exception e)
                
    {
                    sk.cancel();
                    log.info(ExceptionUtil.getExceptionMessage(e));
                }

            }

        }

        
        
    public class Writer implements Runnable 
        
    {
            
    private SelectionKey sk;
            
    private ByteBuffer output;
            
            
    public Writer(SelectionKey sk,ByteBuffer output)
            
    {
                
    this.sk=sk;
                
    this.output=output;
            }

            
            
    public Writer(SelectionKey sk,Future<byte[]> future) throws InterruptedException, ExecutionException
            
    {
                
    this.sk=sk;
                
    this.output=ByteBuffer.wrap(future.get());
            }

            
            @Override
            
    public void run()
            
    {
                SocketChannel sc 
    = (SocketChannel) sk.channel();
                
    try
                
    {
                    
    while(sc.isConnected() && output.hasRemaining())
                    
    {
                        
    int len=sc.write(output);
                        
    if(len<0)
                            
    throw new EOFException();
                        
    else if(len==-1)
                        
    {
                            sk.cancel();
                            sk.selector().selectNow();
                            sc.close();
                        }

                    }

                    
    if(!output.hasRemaining())
                    
    {
                        output.clear();
                        sk.interestOps(SelectionKey.OP_READ);
                        sk.attach(
    new Reader(sk));
                        sk.selector().wakeup();
                    }

                }

                
    catch(Exception e)
                
    {
                    sk.cancel();
                    log.info(ExceptionUtil.getExceptionMessage(e));
                }

            }

        }

        
        
    public void send(SocketChannel sc,byte[] bytes) throws ClosedChannelException
        
    {
            SelectionKey sk
    =sc.register(sel, SelectionKey.OP_WRITE);
            sk.attach(
    new Writer(sk,ByteBuffer.wrap(bytes)));
            sel.wakeup();
        }

    }


    posted on 2013-05-14 16:31 nianzai 閱讀(2727) 評論(1)  編輯  收藏 所屬分類: NIO

    評論:
    # re: JAVA NIO 多線程服務器 1.3版 [未登錄] 2013-09-18 15:34 | z
    Handle 這個方法里面寫的是什么處理呢?能否也貼出來看看  回復  更多評論
      

    只有注冊用戶登錄后才能發(fā)表評論。


    網(wǎng)站導航:
     
    主站蜘蛛池模板: 亚洲三级在线观看| 亚欧色视频在线观看免费| 亚洲校园春色另类激情| 国产亚洲综合网曝门系列| 免费无码又爽又刺激高潮的视频| 在线看片免费人成视久网| 99久久国产精品免费一区二区| 色九月亚洲综合网| 亚洲乱码一区二区三区国产精品| 亚洲欧洲在线观看| 亚洲免费观看视频| 亚洲熟女综合一区二区三区| 亚洲男人天堂av| 亚洲精品国产精品乱码在线观看| 亚洲成aⅴ人片久青草影院| 大学生美女毛片免费视频| 免费福利视频导航| 1a级毛片免费观看| 免费播放一区二区三区| 91福利免费网站在线观看| 一级免费黄色毛片| 日韩免费码中文在线观看| 成a人片亚洲日本久久| 亚洲国产美女精品久久久| 亚洲日本在线电影| 亚洲熟女精品中文字幕| 在线观看亚洲AV日韩A∨| 亚洲区视频在线观看| 亚洲中文字幕无码av在线| 亚洲人成在久久综合网站| 亚洲性猛交xx乱| 久久久久精品国产亚洲AV无码| 亚洲国产成人久久99精品| 亚洲伊人久久精品| 亚洲人xxx日本人18| 亚洲偷自拍另类图片二区| 激情小说亚洲色图| 一二三四在线观看免费中文在线观看| 一级做a爰片性色毛片免费网站| 深夜福利在线视频免费| 久久国产精品免费|