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

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

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

    千里冰封
    JAVA 濃香四溢
    posts - 151,comments - 2801,trackbacks - 0
    早就聽說JAVA的NIO比IO牛一些,可是牛在哪里一直都不知道,并且NIO比IO難學,搞了半天終于用NIO弄了兩個程序,一個是服務器端,一個是客戶端,都是用NIO連接的,代碼如下,注釋比較少,輸出比較多:)

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     
    */
    package testnio;

    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Set;

    /**
     *
     * 
    @author hadeslee
     
    */
    public class Receive {

        
    public static void main(String[] args) throws Exception {
            
    boolean b = true;
            ByteBuffer buffer 
    = ByteBuffer.allocate(1024);
            ServerSocketChannel ss 
    = ServerSocketChannel.open();
            ss.socket().bind(
    new InetSocketAddress(8888));
            ss.configureBlocking(
    false);
            Selector se 
    = Selector.open();
            ss.register(se, SelectionKey.OP_ACCEPT);
            
    while (se.select() > 0) {
                Set
    <SelectionKey> set = se.selectedKeys();
                System.out.println(
    "進入一個循環,大小是:" + set.size());
                
    for (SelectionKey key : set) {
                    
    int ops = key.readyOps();
                    System.out.println(
    "ops=" + ops);
                    
    if ((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                        SocketChannel sc 
    = ss.accept();
                        System.err.println(
    "有新的連接了" + sc);
                        System.err.println(
    "地址是:" + sc.socket());
                        sc.configureBlocking(
    false);
                        sc.register(se, SelectionKey.OP_READ);
                    }
                    
    if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                        System.err.println(
    "有新的讀取");
                        SocketChannel sc 
    = (SocketChannel) key.channel();
                        System.out.println(sc.isConnected());
                        sc.read(buffer);
                        buffer.flip();
                        
    //System.out.println(new String(buffer.array()));
                        Thread.sleep(5000);
                        
    if (b) {
                            b 
    = false;
                            sc.write(buffer);
                        }

                    }
                }
                set.clear();
                System.out.println(
    "退出循環");
            }

        }
    }

    客戶端:

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     
    */
    package testnio;

    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Set;

    /**
     *
     * 
    @author hadeslee
     
    */
    public class Send {

        
    public static void main(String[] args) throws Exception {
            SocketChannel sc 
    = SocketChannel.open();
            ByteBuffer buffer 
    = ByteBuffer.allocate(1024);
            Selector se 
    = Selector.open();
            buffer.put(
    "我是中國人,我愛我的祖國,hadeslee".getBytes());
            buffer.flip();
            
            sc.configureBlocking(
    false);
            sc.register(se, SelectionKey.OP_CONNECT 
    | SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            sc.connect(
    new InetSocketAddress("192.168.1.58"8888));
            
    while(!sc.finishConnect());
            sc.write(buffer);
            System.out.println(
    "進入循環");
            Thread.sleep(
    10000);
            
    int sum = se.select();
            
    while (se.select() > 0) {
                Thread.sleep(
    100);
                   
                    System.out.println(
    "終于大于0了");
                    Set
    <SelectionKey> set = se.selectedKeys();
                    System.out.println(
    "大小是:"+set.size());
                    
    for (SelectionKey key : set) {
                        
    int ops = key.readyOps();
                        
    if ((ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                            sc.write(buffer);
                            System.out.println(
    "連接成功");
                        }
                        
    if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                            System.out.println(
    " 收到東西");
                            sc.read(buffer);
                            buffer.flip();
                            System.out.println(
    "收到的是:" + new String(buffer.array(),0,buffer.limit()));
                            sc.write(buffer);
                        }
                    }
                   se.selectedKeys().clear();
            }
        }

        
    private static ByteBuffer[] get(String heads) {
            ByteBuffer[] bbs 
    = new ByteBuffer[heads.length];
            
    for (int i = 0; i < bbs.length; i++) {
                String s 
    = heads[i];
                bbs[i] 
    = ByteBuffer.allocateDirect(1024);
                bbs[i].put(s.getBytes());
                bbs[i].flip();
            }
            
    return bbs;
        }
    }
    有機會再好好研究它們之間的更加具體的用法,以上的只是一個簡單的,能互連的一個例子.




    盡管千里冰封
    依然擁有晴空

    你我共同品味JAVA的濃香.
    posted on 2007-11-05 10:50 千里冰封 閱讀(16759) 評論(8)  編輯  收藏 所屬分類: JAVASE

    FeedBack:
    # re: NIO連接socket
    2007-11-05 11:48 | Michael Zheng
    沒看代碼 :) 就是看到了NIO IO就進來看看 哈哈啊

    據Thinking In Java 說,Java 中的IO用NIO重寫過了

    所以效率差別不大 :)

    大家討論討論啊  回復  更多評論
      
    # re: NIO連接socket
    2007-11-05 13:18 | 詩特林
    java5里的NIO我覺得比IO還是改進比較大的.不信去運行一下Thinking in Java 4th版里的相關例子.我試過,要快些,當然,NIO做了不少擴展,  回復  更多評論
      
    # re: NIO連接socket
    2008-04-05 16:44 | fenixshadow
    Apache Mina是一個NIO框架,用來實現socket服務端非常方便。

    用他們的廣告語來說就是:

    Convert ByteBuffer to String for free!


    不過實現客戶端有點麻煩。  回復  更多評論
      
    # re: NIO連接socket
    2008-07-07 16:04 | 冰河の泥魚
    哈哈,你寫的代碼,在我這里編譯不通過。我使用的是JDK1.6+eclipse3.3.2,老大是不是應該測試后再發上來呢?  回復  更多評論
      
    # re: NIO連接socket[未登錄]
    2008-07-07 17:34 | 小小
    @冰河の泥魚
    哪里編譯通不過,提示第幾行?
    我這里都可以編譯通過的啊.  回復  更多評論
      
    # re: NIO連接socket
    2008-07-08 11:18 | 冰河の泥魚
    @小小
    一,簡單的錯誤:
    private static ByteBuffer[] get(String heads)中的:
    heads.length=>heads.length()
    heads[i] ---The type of the expression must be an array type but it resolved to String

    經過核對CODE,該方法從未被使用.故稱之為簡單錯誤.

    剛剛又把你的源碼再次復制粘貼,竟然可以了.不過方法"private static ByteBuffer[] get(String heads)"寫得還是有問題.請驗證.

      回復  更多評論
      
    # re: NIO連接socket
    2008-07-08 14:03 | 千里冰封
    @冰河の泥魚
    private static ByteBuffer[] get(String... heads)
    可能是你復制過去的時候沒有發現String后面有三個點哦,呵呵,這是JDK1.5新加的可變參數,它表示的就是一個String[] heads
    我也復制了一下代碼,那三個點確實復制不下來. blogjava的代碼塊還是有點問題的  回復  更多評論
      
    # re: NIO連接socket
    2011-06-17 13:32 | epinszteinic
    @千里冰封
    那三個點它是用圖片做的,當然復制不下來了。。。  回復  更多評論
      
    主站蜘蛛池模板: 香蕉成人免费看片视频app下载| 大桥未久亚洲无av码在线| 中文字幕版免费电影网站| 国产真实伦在线视频免费观看| 亚洲色偷偷综合亚洲av78| 亚洲黄色免费网址| 亚洲一区影音先锋色资源| 久久国产精品免费网站| 国产av天堂亚洲国产av天堂| 丝瓜app免费下载网址进入ios | 久久精品亚洲AV久久久无码| 热re99久久6国产精品免费| 久久久久久久久亚洲| 一级毛片在线观看免费| 亚洲色图国产精品| 毛片免费全部播放无码| 亚洲AV无码成人专区| 女人张开腿给人桶免费视频| 久久亚洲AV成人无码国产电影 | 1000部禁片黄的免费看| 亚洲男人天堂影院| 无码人妻一区二区三区免费 | 午夜亚洲国产理论片二级港台二级 | 亚洲一区二区三区国产精品| 和老外3p爽粗大免费视频| 久久精品国产亚洲沈樵| **aaaaa毛片免费| 亚洲精品女同中文字幕| 亚洲欧洲国产成人综合在线观看 | 国产黄色免费网站| 亚洲无码一区二区三区| 亚洲福利精品电影在线观看| 免费精品99久久国产综合精品| 亚洲国产精品午夜电影| 性做久久久久免费看| 成人精品视频99在线观看免费| 亚洲理论精品午夜电影| 国产v片免费播放| 久久精品中文字幕免费| 久久久久久亚洲精品影院| 精品国产亚洲男女在线线电影 |