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

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

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

    隨筆-57  評論-202  文章-17  trackbacks-0
          最近在做有關(guān)Socket的程序,寫了兩個客戶端程序,第一個客戶端程序如下:

     1package sample.nio;
     2
     3import java.io.IOException;
     4import java.net.*;
     5import java.nio.ByteBuffer;
     6import java.nio.channels.*;
     7
     8/**
     9 * <p>Title: </p>
    10 *
    11 * <p>Description: </p>
    12 *
    13 * <p>Copyright: Copyright (c) 2005</p>
    14 *
    15 * <p>Company: </p>
    16 *
    17 * @author George Hill
    18 * @version 1.0
    19 */

    20
    21public class Client1 {
    22
    23  private static final String EXIT = "EXIT";
    24
    25  private InetAddress host;
    26  private int port;
    27
    28  public Client1(InetAddress host, int port) {
    29    this.host = host;
    30    this.port = port;
    31  }

    32
    33  public void startClient() throws IOException {
    34    // 創(chuàng)建SocketChannel
    35    SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));
    36    channel.configureBlocking(false);
    37
    38    int read = 0;
    39    ByteBuffer buffer = ByteBuffer.allocate(1024);
    40
    41    System.out.println("Client Start");
    42
    43    int i = 0;
    44    while ((read = channel.read(buffer)) != -1{
    45      if (read == 0{
    46        System.out.println(i++ + " read a null string");
    47        try {
    48          Thread.sleep(1000);
    49        }
     catch (InterruptedException ie) {
    50        }

    51      }

    52
    53      buffer.flip();
    54      byte[] array = new byte[read];
    55      buffer.get(array);
    56      String s = new String(array);
    57      System.out.print(s);
    58      buffer.clear();
    59
    60      if (s.endsWith(EXIT)) {
    61        System.out.println();
    62      }

    63    }

    64
    65    channel.close();
    66    System.out.println("Client Stop");
    67  }

    68
    69  public static void main(String[] args) throws Exception {
    70    Client1 client = new Client1(InetAddress.getLocalHost(), 5000);
    71    client.startClient();
    72  }

    73}

    74


          這個客戶端程序類似于傳統(tǒng)的IO客戶端程序,只是在36行設(shè)定為非阻塞,如果這里設(shè)置成true,那么和傳統(tǒng)的IO實現(xiàn)沒有什么很大的區(qū)別。不過,這個程序有一個很大的問題,由于在36行設(shè)置成非阻塞的IO,所在在讀的時候是不會阻塞的,那么在44行的while循環(huán)會不停的執(zhí)行,可以看到輸出很多“read a null string”。如果在這里不強制進行線程睡眠,CPU資源很快就耗盡。

          改進的方法是使用Selector,下面是另外一個客戶端的實現(xiàn):

     1package sample.nio;
     2
     3import java.io.IOException;
     4import java.net.*;
     5import java.nio.ByteBuffer;
     6import java.nio.channels.*;
     7import java.util.*;
     8
     9/**
    10 * <p>Title: </p>
    11 *
    12 * <p>Description: </p>
    13 *
    14 * <p>Copyright: Copyright (c) 2005</p>
    15 *
    16 * <p>Company: </p>
    17 *
    18 * @author George Hill
    19 * @version 1.0
    20 */

    21
    22public class Client2 {
    23
    24  private static final String EXIT = "EXIT";
    25
    26  private InetAddress host;
    27  private int port;
    28
    29  public Client2(InetAddress host, int port) {
    30    this.host = host;
    31    this.port = port;
    32  }

    33
    34  public void startClient() throws IOException {
    35    // 創(chuàng)建SocketChannel
    36    SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));
    37    channel.configureBlocking(false);
    38
    39    // 創(chuàng)建Selector
    40    Selector selector = Selector.open();
    41    // 向Selector注冊我們需要的READ事件
    42    SelectionKey skey = channel.register(selector, SelectionKey.OP_READ);
    43
    44    boolean stop = false;
    45    int n = 0;
    46    int read = 0;
    47    ByteBuffer buffer = ByteBuffer.allocate(1024);
    48
    49    System.out.println("Client Start");
    50
    51    // 輪詢
    52    while (!stop) {
    53      // 獲取Selector返回的時間值
    54      n = selector.select();
    55
    56      // 當傳回的值大于0事,讀時間發(fā)生了
    57      if (n > 0{
    58        Set set = selector.selectedKeys();
    59        Iterator it = set.iterator();
    60
    61        while (it.hasNext()) {
    62          skey = (SelectionKey) it.next();
    63          it.remove();
    64
    65          if (skey.isReadable()) {
    66            SocketChannel sc = (SocketChannel) skey.channel();
    67
    68            while ((read = sc.read(buffer)) != -1{
    69              if (read == 0)
    70                break;
    71
    72              buffer.flip();
    73              byte[] array = new byte[read];
    74              buffer.get(array);
    75              String s = new String(array);
    76              System.out.print(s);
    77              buffer.clear();
    78
    79              if (s.endsWith(EXIT)) {
    80                stop = true;
    81                System.out.println();
    82              }

    83            }

    84          }

    85        }

    86      }

    87    }

    88
    89    channel.close();
    90    System.out.println("Client Stop");
    91  }

    92
    93  public static void main(String[] args) throws Exception {
    94    Client2 client = new Client2(InetAddress.getLocalHost(), 5000);
    95    client.startClient();
    96  }

    97}

    98

          由于使用了Selector,程序只有當注冊的事件發(fā)生時,才會繼續(xù)執(zhí)行,所以在這里不需要再用線程睡眠的方式去釋放CPU資源。
    posted on 2005-05-18 12:18 小米 閱讀(3888) 評論(1)  編輯  收藏 所屬分類: Java

    評論:
    # re: 用NIO實現(xiàn)的兩種網(wǎng)絡(luò)程序客戶端[未登錄] 2011-09-15 15:11 | 阿土
    這是客戶端的吧?  回復  更多評論
      
    主站蜘蛛池模板: 成全视频在线观看免费| 中文字幕不卡亚洲| 最刺激黄a大片免费网站| 美女黄色免费网站| 亚洲一区二区三区在线网站| 国产成人精品日本亚洲| 亚洲A∨午夜成人片精品网站| 可以免费看黄视频的网站| 久久黄色免费网站| 99re6在线视频精品免费| 未满十八私人高清免费影院| 亚洲另类无码专区丝袜| 亚洲一区二区三区在线网站| 91在线亚洲精品专区| 亚洲av色影在线| 亚洲国产综合无码一区| 亚洲一区二区女搞男| 亚洲视频在线免费| 亚洲精品国精品久久99热| 又粗又硬免费毛片| 国产中文字幕免费| 免费看男女下面日出水视频| 香蕉视频在线观看免费国产婷婷| 免费电视剧在线观看| 香蕉97超级碰碰碰免费公| 久久午夜免费视频| 最近中文字幕mv手机免费高清| 99无码人妻一区二区三区免费| 国产精品久久久久久久久免费| 亚洲免费在线视频观看| 成年在线观看网站免费| 好男人www免费高清视频在线| 国产精品成人免费视频网站京东| 精品久久久久久久久免费影院| 成人AV免费网址在线观看| 免费看国产成年无码AV片| 在线看片无码永久免费aⅴ| 国产大片51精品免费观看| 亚洲 综合 国产 欧洲 丝袜| 亚洲欧洲久久久精品| 亚洲综合av永久无码精品一区二区 |