使用SocketChannel的NIO客戶機服務器通信示例。(轉)


http://www.cnblogs.com/likwo/archive/2010/06/29/1767814.html

NIO Selector示意圖:


客戶端代碼:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;


/**
 * NIO TCP 客戶端
 * 
 * @date    2010-2-3
 * @time    下午03:33:26
 * @version 1.00
 */
public class TCPClient{
  // 信道選擇器
  private Selector selector;
  
  // 與服務器通信的信道
  SocketChannel socketChannel;
  
  // 要連接的服務器Ip地址
  private String hostIp;
  
  // 要連接的遠程服務器在監聽的端口
  private int hostListenningPort;
  
  /**
   * 構造函數
   * @param HostIp
   * @param HostListenningPort
   * @throws IOException
   */
  public TCPClient(String HostIp,int HostListenningPort)throws IOException{
    this.hostIp=HostIp;
    this.hostListenningPort=HostListenningPort;   
    
    initialize();
  }
  
  /**
   * 初始化
   * @throws IOException
   */
  private void initialize() throws IOException{
    // 打開監聽信道並設置爲非阻塞模式
    socketChannel=SocketChannel.open(new InetSocketAddress(hostIp, hostListenningPort));
    socketChannel.configureBlocking(false);
    
    // 打開並註冊選擇器到信道
    selector = Selector.open();
    socketChannel.register(selector, SelectionKey.OP_READ);
    
    // 啓動讀取線程
    new TCPClientReadThread(selector);
  }
  
  /**
   * 發送字符串到服務器
   * @param message
   * @throws IOException
   */
  public void sendMsg(String message) throws IOException{
    ByteBuffer writeBuffer=ByteBuffer.wrap(message.getBytes("UTF-16"));
    socketChannel.write(writeBuffer);
  }
  
  public static void main(String[] args) throws IOException{
    TCPClient client=new TCPClient("192.168.0.1",1978);
    
    client.sendMsg("你好!Nio!醉裏挑燈看劍,夢迴吹角連營");
  }
}


客戶端讀取線程代碼:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class TCPClientReadThread implements Runnable{
  private Selector selector;
  
  public TCPClientReadThread(Selector selector){
    this.selector=selector;
    
    new Thread(this).start();
  }
  
  public void run() {
    try {
      while (selector.select() > 0) {
        // 遍歷每個有可用IO操作Channel對應的SelectionKey
        for (SelectionKey sk : selector.selectedKeys()) {
          
          // 如果該SelectionKey對應的Channel中有可讀的數據
          if (sk.isReadable()) {
            // 使用NIO讀取Channel中的數據
            SocketChannel sc = (SocketChannel) sk.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            sc.read(buffer);
            buffer.flip();
            
            // 將字節轉化爲爲UTF-16的字符串   
            String receivedString=Charset.forName("UTF-16").newDecoder().decode(buffer).toString();
            
            // 控制檯打印出來
            System.out.println("接收到來自服務器"+sc.socket().getRemoteSocketAddress()+"的信息:"+receivedString);
            
            // 爲下一次讀取作準備
            sk.interestOps(SelectionKey.OP_READ);
          }
          
          // 刪除正在處理的SelectionKey
          selector.selectedKeys().remove(sk);
        }
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }   
  }
}


服務器端代碼:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

/**
 * TCP服務器端 
 * 
 * @date    2010-2-3
 * @time    上午08:39:48
 * @version 1.00
 */
public class TCPServer{
  // 緩衝區大小
  private static final int BufferSize=1024;
  
  // 超時時間,單位毫秒
  private static final int TimeOut=3000;
  
  // 本地監聽端口
  private static final int ListenPort=1978;
  
  public static void main(String[] args) throws IOException{
    // 創建選擇器
    Selector selector=Selector.open();
    
    // 打開監聽信道
    ServerSocketChannel listenerChannel=ServerSocketChannel.open();
    
    // 與本地端口綁定
    listenerChannel.socket().bind(new InetSocketAddress(ListenPort));
    
    // 設置爲非阻塞模式
    listenerChannel.configureBlocking(false);
    
    // 將選擇器綁定到監聽信道,只有非阻塞信道纔可以註冊選擇器.並在註冊過程中指出該信道可以進行Accept操作
    listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
    
    // 創建一個處理協議的實現類,由它來具體操作
    TCPProtocol protocol=new TCPProtocolImpl(BufferSize);
    
    // 反覆循環,等待IO
    while(true){
      // 等待某信道就緒(或超時)
      if(selector.select(TimeOut)==0){
        System.out.print("獨自等待.");
        continue;
      }
      
      // 取得迭代器.selectedKeys()中包含了每個準備好某一I/O操作的信道的SelectionKey
      Iterator<SelectionKey> keyIter=selector.selectedKeys().iterator();
      
      while(keyIter.hasNext()){
        SelectionKey key=keyIter.next();
        
        try{
          if(key.isAcceptable()){
            // 有客戶端連接請求時
            protocol.handleAccept(key);
          }
          
          if(key.isReadable()){
            // 從客戶端讀取數據
            protocol.handleRead(key);
          }
          
          if(key.isValid() && key.isWritable()){
            // 客戶端可寫時
            protocol.handleWrite(key);
          }
        }
        catch(IOException ex){
          // 出現IO異常(如客戶端斷開連接)時移除處理過的鍵
          keyIter.remove();
          continue;
        }
        
        // 移除處理過的鍵
        keyIter.remove();
      }
    }
  }
}


協議接口代碼:

import java.io.IOException;
import java.nio.channels.SelectionKey;

/**
 * TCPServerSelector與特定協議間通信的接口
 * 
 * @date    2010-2-3
 * @time    上午08:42:42
 * @version 1.00
 */
public interface TCPProtocol{
  /**
   * 接收一個SocketChannel的處理
   * @param key
   * @throws IOException
   */
  void handleAccept(SelectionKey key) throws IOException;
  
  /**
   * 從一個SocketChannel讀取信息的處理
   * @param key
   * @throws IOException
   */
  void handleRead(SelectionKey key) throws IOException;
  
  /**
   * 向一個SocketChannel寫入信息的處理
   * @param key
   * @throws IOException
   */
  void handleWrite(SelectionKey key) throws IOException;
}


協議實現類代碼:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * TCPProtocol的實現類
 * 
 * @date    2010-2-3
 * @time    上午08:58:59
 * @version 1.00
 */
public class TCPProtocolImpl implements TCPProtocol{
  private int bufferSize;
  
  public TCPProtocolImpl(int bufferSize){
    this.bufferSize=bufferSize;
  }

  public void handleAccept(SelectionKey key) throws IOException {
    SocketChannel clientChannel=((ServerSocketChannel)key.channel()).accept();
    clientChannel.configureBlocking(false);
    clientChannel.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocate(bufferSize));
  }

  public void handleRead(SelectionKey key) throws IOException {
    // 獲得與客戶端通信的信道
    SocketChannel clientChannel=(SocketChannel)key.channel();
    
    // 得到並清空緩衝區
    ByteBuffer buffer=(ByteBuffer)key.attachment();
    buffer.clear();
    
    // 讀取信息獲得讀取的字節數
    long bytesRead=clientChannel.read(buffer);
    
    if(bytesRead==-1){
      // 沒有讀取到內容的情況
      clientChannel.close();
    }
    else{
      // 將緩衝區準備爲數據傳出狀態
      buffer.flip();
      
      // 將字節轉化爲爲UTF-16的字符串   
      String receivedString=Charset.forName("UTF-16").newDecoder().decode(buffer).toString();
      
      // 控制檯打印出來
      System.out.println("接收到來自"+clientChannel.socket().getRemoteSocketAddress()+"的信息:"+receivedString);
      
      // 準備發送的文本
      String sendString="你好,客戶端. @"+new Date().toString()+",已經收到你的信息"+receivedString;
      buffer=ByteBuffer.wrap(sendString.getBytes("UTF-16"));
      clientChannel.write(buffer);
      
      // 設置爲下一次讀取或是寫入做準備
      key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    }
  }

  public void handleWrite(SelectionKey key) throws IOException {
    // do nothing
  }
}


 

http://www.blogjava.net/longturi/archive/2010/02/03/311820.html

 

另外一篇比較好的文章

http://www.oschina.net/question/54100_33530

發佈了180 篇原創文章 · 獲贊 52 · 訪問量 92萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章