<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 多線程服務(wù)器,這是比較完善的一版了。Java 的 NIO 網(wǎng)絡(luò)模型實(shí)在是不好用,還是使用現(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 閱讀(2736) 評論(1)  編輯  收藏 所屬分類: NIO

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

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


    網(wǎng)站導(dǎo)航:
     
    主站蜘蛛池模板: 操美女视频免费网站| 阿v免费在线观看| 亚洲国产日产无码精品| 亚洲资源在线观看| 亚洲国产精品久久久久网站| 亚洲av无码不卡| 亚洲国产香蕉碰碰人人| 亚洲五月六月丁香激情| 亚洲黄色三级视频| 亚洲人成综合在线播放| 中文字幕无码亚洲欧洲日韩| 亚洲精品国产suv一区88| 亚洲av无码专区首页| 狠狠热精品免费观看| xxxxx做受大片视频免费| 全黄大全大色全免费大片| 毛片在线播放免费观看| 91福利免费体验区观看区| 999国内精品永久免费视频| 毛片A级毛片免费播放| 免费看少妇作爱视频| 无码欧精品亚洲日韩一区夜夜嗨| 亚洲区不卡顿区在线观看| 亚洲VA中文字幕不卡无码| 亚洲精品美女在线观看| 亚洲精品无码人妻无码| 美女被爆羞羞网站在免费观看| 亚洲免费日韩无码系列| 无码国产精品一区二区免费16 | 亚洲不卡影院午夜在线观看| 久久人午夜亚洲精品无码区| 一级做a爰片久久毛片免费看| 久久国产乱子精品免费女| 18禁免费无码无遮挡不卡网站| 国内自产少妇自拍区免费| 亚洲人成无码久久电影网站| 亚洲尹人香蕉网在线视颅| 亚洲女子高潮不断爆白浆| 精品国产污污免费网站入口在线| 一级毛片全部免费播放| 精品免费国产一区二区|