<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難學(xué),搞了半天終于用NIO弄了兩個程序,一個是服務(wù)器端,一個是客戶端,都是用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(
    "進(jìn)入一個循環(huán),大小是:" + 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(
    "退出循環(huán)");
            }

        }
    }

    客戶端:

    /*
     * 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(
    "進(jìn)入循環(huán)");
            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 千里冰封 閱讀(16770) 評論(8)  編輯  收藏 所屬分類: JAVASE

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

    據(jù)Thinking In Java 說,Java 中的IO用NIO重寫過了

    所以效率差別不大 :)

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

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

    Convert ByteBuffer to String for free!


    不過實現(xiàn)客戶端有點麻煩。  回復(fù)  更多評論
      
    # re: NIO連接socket
    2008-07-07 16:04 | 冰河の泥魚
    哈哈,你寫的代碼,在我這里編譯不通過。我使用的是JDK1.6+eclipse3.3.2,老大是不是應(yīng)該測試后再發(fā)上來呢?  回復(fù)  更多評論
      
    # re: NIO連接socket[未登錄]
    2008-07-07 17:34 | 小小
    @冰河の泥魚
    哪里編譯通不過,提示第幾行?
    我這里都可以編譯通過的啊.  回復(fù)  更多評論
      
    # 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

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

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

      回復(fù)  更多評論
      
    # re: NIO連接socket
    2008-07-08 14:03 | 千里冰封
    @冰河の泥魚
    private static ByteBuffer[] get(String... heads)
    可能是你復(fù)制過去的時候沒有發(fā)現(xiàn)String后面有三個點哦,呵呵,這是JDK1.5新加的可變參數(shù),它表示的就是一個String[] heads
    我也復(fù)制了一下代碼,那三個點確實復(fù)制不下來. blogjava的代碼塊還是有點問題的  回復(fù)  更多評論
      
    # re: NIO連接socket
    2011-06-17 13:32 | epinszteinic
    @千里冰封
    那三個點它是用圖片做的,當(dāng)然復(fù)制不下來了。。。  回復(fù)  更多評論
      
    主站蜘蛛池模板: 亚洲国产成人精品激情| 亚洲中文无码永久免费| 又爽又高潮的BB视频免费看| 亚洲区精品久久一区二区三区| 久久久久久国产精品免费免费男同| 亚洲人成亚洲人成在线观看| 三年片免费观看大全国语| 国产亚洲成人久久| 成人午夜影视全部免费看| 免费少妇a级毛片| 日本一卡精品视频免费| 亚洲精品**中文毛片| 真人做A免费观看| 亚洲国产成人手机在线电影bd| 免费a级毛片永久免费| 91精品免费不卡在线观看| 中文字幕亚洲综合精品一区| 99久久国产免费中文无字幕| 亚洲va中文字幕| 亚洲午夜无码AV毛片久久| 国产午夜免费高清久久影院| 久久精品国产亚洲AV嫖农村妇女 | 亚在线观看免费视频入口| 亚洲国产欧洲综合997久久| 亚洲欧洲第一a在线观看| 国产精品视频免费观看| 深夜免费在线视频| 亚洲人成图片网站| 日韩精品电影一区亚洲| h视频免费高清在线观看| 好看的亚洲黄色经典| 亚洲视频免费播放| 色偷偷尼玛图亚洲综合| 亚洲一级特黄大片在线观看 | 欧美好看的免费电影在线观看| 亚洲GV天堂GV无码男同| 亚洲成年人电影网站| 国产又黄又爽又猛的免费视频播放 | 亚洲精品成人区在线观看| 香蕉免费一级视频在线观看| 亚洲综合男人的天堂色婷婷|