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

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

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

    paulwong

    NIO Socket非阻塞模式

    Server socket編程的時(shí)候,一個(gè)SERVER服務(wù)一個(gè)連接的時(shí)候,是阻塞線程的,除非用多線程來處理。

    NIO只使用一條線程即可以處理多個(gè)連接。是基于事件的模式,即產(chǎn)生事件的時(shí)候,通知客戶端處理相應(yīng)的事件。

    1)server端代碼
        /** 
         *  
         * 
    @author Jeff 
         * 
         
    */  
        
    public class HelloWorldServer {  
          
            
    static int BLOCK = 1024;  
            
    static String name = "";  
            
    protected Selector selector;  
            
    protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);  
            
    protected CharsetDecoder decoder;  
            
    static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();  
          
            
    public HelloWorldServer(int port) throws IOException {  
                selector 
    = this.getSelector(port);  
                Charset charset 
    = Charset.forName("GB2312");  
                decoder 
    = charset.newDecoder();  
            }  
          
            
    // 獲取Selector  
            protected Selector getSelector(int port) throws IOException {  
                ServerSocketChannel server 
    = ServerSocketChannel.open();  
                Selector sel 
    = Selector.open();  
                server.socket().bind(
    new InetSocketAddress(port));  
                server.configureBlocking(
    false);  
                server.register(sel, SelectionKey.OP_ACCEPT);  
                
    return sel;  
            }  
          
            
    // 監(jiān)聽端口  
            public void listen() {  
                
    try {  
                    
    for (;;) {  
                        selector.select();  
                        Iterator iter 
    = selector.selectedKeys().iterator();  
                        
    while (iter.hasNext()) {  
                            SelectionKey key 
    = (SelectionKey) iter.next();  
                            iter.remove();  
                            process(key);  
                        }  
                    }  
                } 
    catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
          
            
    // 處理事件  
            protected void process(SelectionKey key) throws IOException {  
                
    if (key.isAcceptable()) { // 接收請(qǐng)求  
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();  
                    SocketChannel channel 
    = server.accept();  
                    
    //設(shè)置非阻塞模式  
                    channel.configureBlocking(false);  
                    channel.register(selector, SelectionKey.OP_READ);  
                } 
    else if (key.isReadable()) { // 讀信息  
                    SocketChannel channel = (SocketChannel) key.channel();  
                    
    int count = channel.read(clientBuffer);  
                    
    if (count > 0) {  
                        clientBuffer.flip();  
                        CharBuffer charBuffer 
    = decoder.decode(clientBuffer);  
                        name 
    = charBuffer.toString();  
                        
    // System.out.println(name);  
                        SelectionKey sKey = channel.register(selector,  
                                SelectionKey.OP_WRITE);  
                        sKey.attach(name);  
                    } 
    else {  
                        channel.close();  
                    }  
          
                    clientBuffer.clear();  
                } 
    else if (key.isWritable()) { // 寫事件  
                    SocketChannel channel = (SocketChannel) key.channel();  
                    String name 
    = (String) key.attachment();  
                      
                    ByteBuffer block 
    = encoder.encode(CharBuffer  
                            .wrap(
    "Hello !" + name));  
                      
          
                    channel.write(block);  
          
                    
    //channel.close();  
          
                }  
            }  
          
            
    public static void main(String[] args) {  
                
    int port = 8888;  
                
    try {  
                    HelloWorldServer server 
    = new HelloWorldServer(port);  
                    System.out.println(
    "listening on " + port);  
                      
                    server.listen();  
                      
                } 
    catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }


    server主要是讀取client發(fā)過來的信息,并返回一條信息

    2)client端代碼
        /** 
         *  
         * 
    @author Jeff 
         * 
         
    */  
        
    public class HelloWorldClient {  
          
            
    static int SIZE = 10;  
            
    static InetSocketAddress ip = new InetSocketAddress("localhost"8888);  
            
    static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();  
          
            
    static class Message implements Runnable {  
                
    protected String name;  
                String msg 
    = "";  
          
                
    public Message(String index) {  
                    
    this.name = index;  
                }  
          
                
    public void run() {  
                    
    try {  
                        
    long start = System.currentTimeMillis();  
                        
    //打開Socket通道  
                        SocketChannel client = SocketChannel.open();  
                        
    //設(shè)置為非阻塞模式  
                        client.configureBlocking(false);  
                        
    //打開選擇器  
                        Selector selector = Selector.open();  
                        
    //注冊(cè)連接服務(wù)端socket動(dòng)作  
                        client.register(selector, SelectionKey.OP_CONNECT);  
                        
    //連接  
                        client.connect(ip);  
                        
    //分配內(nèi)存  
                        ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);  
                        
    int total = 0;  
          
                        _FOR: 
    for (;;) {  
                            selector.select();  
                            Iterator iter 
    = selector.selectedKeys().iterator();  
          
                            
    while (iter.hasNext()) {  
                                SelectionKey key 
    = (SelectionKey) iter.next();  
                                iter.remove();  
                                
    if (key.isConnectable()) {  
                                    SocketChannel channel 
    = (SocketChannel) key  
                                            .channel();  
                                    
    if (channel.isConnectionPending())  
                                        channel.finishConnect();  
                                    channel  
                                            .write(encoder  
                                                    .encode(CharBuffer.wrap(name)));  
          
                                    channel.register(selector, SelectionKey.OP_READ);  
                                } 
    else if (key.isReadable()) {  
                                    SocketChannel channel 
    = (SocketChannel) key  
                                            .channel();  
                                    
    int count = channel.read(buffer);  
                                    
    if (count > 0) {  
                                        total 
    += count;  
                                        buffer.flip();  
          
                                        
    while (buffer.remaining() > 0) {  
                                            
    byte b = buffer.get();  
                                            msg 
    += (char) b;  
                                              
                                        }  
          
                                        buffer.clear();  
                                    } 
    else {  
                                        client.close();  
                                        
    break _FOR;  
                                    }  
                                }  
                            }  
                        }  
                        
    double last = (System.currentTimeMillis() - start) * 1.0 / 1000;  
                        System.out.println(msg 
    + "used time :" + last + "s.");  
                        msg 
    = "";  
                    } 
    catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
          
            
    public static void main(String[] args) throws IOException {  
              
                String names[] 
    = new String[SIZE];  
          
                
    for (int index = 0; index < SIZE; index++) {  
                    names[index] 
    = "jeff[" + index + "]";  
                    
    new Thread(new Message(names[index])).start();  
                }  
              
            }  
        }




    posted on 2013-03-31 13:38 paulwong 閱讀(356) 評(píng)論(0)  編輯  收藏 所屬分類: J2SE性能優(yōu)化

    主站蜘蛛池模板: 在线观看无码的免费网站| 野花高清在线电影观看免费视频| 亚洲精品视频免费观看| 一级成人a免费视频| 中文字幕无码免费久久9一区9| a级毛片无码免费真人久久| 日本亚洲欧洲免费天堂午夜看片女人员 | 国产大片免费天天看| 国产又大又粗又长免费视频| 毛片免费vip会员在线看| 国产禁女女网站免费看| 久久久久一级精品亚洲国产成人综合AV区 | 无人在线观看免费高清| 国产精彩免费视频| 亚洲天堂在线视频| 久久久久亚洲AV无码麻豆| 亚洲男人天堂2018av| 无码毛片一区二区三区视频免费播放| 99视频免费在线观看| 免费看片免费播放| 亚洲午夜久久久久久久久电影网| 亚洲精品免费在线| 国产成人精品久久亚洲高清不卡| 美女被免费网站91色| 57PAO成人国产永久免费视频| 国产AV无码专区亚洲AV漫画| 亚洲网站在线播放| 国产精品无码永久免费888| 免费鲁丝片一级观看| 亚洲成人午夜电影| 特色特黄a毛片高清免费观看| 久久午夜免费视频| 久久精品国产亚洲Aⅴ香蕉| 亚洲精华国产精华精华液好用| 国产午夜不卡AV免费| 免费被黄网站在观看| 亚洲欧洲精品一区二区三区| 99久久婷婷免费国产综合精品| 内射无码专区久久亚洲| 亚洲视频在线观看地址| 一级做a爰片久久毛片免费陪 |