千里冰封
          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 千里冰封 閱讀(16765) 評論(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
          @千里冰封
          那三個點它是用圖片做的,當然復制不下來了。。。  回復  更多評論
            
          主站蜘蛛池模板: 东台市| 正阳县| 长宁县| 贵定县| 泸定县| 林口县| 台南县| 宾川县| 温泉县| 锡林郭勒盟| 阿合奇县| 东光县| 雷山县| 姜堰市| 山东省| 蕲春县| 永川市| 桓仁| 平定县| 日照市| 广丰县| 尤溪县| 天镇县| 金坛市| 循化| 化隆| 广元市| 临颍县| 屏南县| 布尔津县| 湄潭县| 宁明县| 绥棱县| 陵水| 江口县| 鄂托克旗| 水城县| 满城县| 柳州市| 广元市| 图片|