<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 網絡模型實在是不好用,還是使用現成的好。
    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 閱讀(2729) 評論(1)  編輯  收藏 所屬分類: NIO

    評論:
    # re: JAVA NIO 多線程服務器 1.3版 [未登錄] 2013-09-18 15:34 | z
    Handle 這個方法里面寫的是什么處理呢?能否也貼出來看看  回復  更多評論
      
    主站蜘蛛池模板: 久久精品无码专区免费东京热| 成人午夜性A级毛片免费| 四虎影视在线影院在线观看免费视频| 99精品视频免费观看| 国产视频精品免费| 91精品国产亚洲爽啪在线观看| 国内成人精品亚洲日本语音| 免费无码成人AV在线播放不卡| 亚洲视频在线播放| 一级毛片成人免费看a| 麻豆国产VA免费精品高清在线| 亚洲av无码国产精品色午夜字幕| 久久亚洲AV成人无码国产电影| 日韩精品免费在线视频| 亚洲人成影院在线观看| 久久亚洲精品高潮综合色a片| 日本无吗免费一二区| 亚洲国产福利精品一区二区| 久久久久久久99精品免费| 亚洲日本在线观看| 妞干网免费视频在线观看| 亚洲国产精品综合久久网各| 免费无码黄网站在线看| 中文字幕中韩乱码亚洲大片| 国产亚洲午夜精品| 国产成人精品日本亚洲网站| 精品人妻系列无码人妻免费视频| 免费国内精品久久久久影院| 亚洲av无码有乱码在线观看| 国产亚洲成归v人片在线观看| 亚洲一区免费观看| 亚洲国产一区二区三区在线观看| 99爱在线精品免费观看| 亚洲一区在线视频| 67194成是人免费无码| 亚洲 暴爽 AV人人爽日日碰| 欧美a级在线现免费观看| 一级毛片免费观看不收费| 亚洲欧洲国产精品久久| www.亚洲一区| 成在线人免费无码高潮喷水|