7.Java NIO系列教程之Server/Client完整示例
TCPServer類:
package com.gw.demo; 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; import java.util.Set; 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操作 //一個server socket channel準備好接收新進入的連線稱為“接收就緒” listenerChannel.register(selector, SelectionKey.OP_ACCEPT); // 建立一個處理協議的實現類,由它來具體操作 TCPProtocol protocol = new TCPProtocolImpl(BufferSize); // 反覆迴圈,等待IO while (true) { // 等待某通道就緒(或超時) int keys = selector.select(TimeOut); //剛啟動時連續輸出0,client連線後一直輸出1 //System.out.print(keys); if (keys == 0) { System.out.println("獨自等待."); continue; } /*if (selector.select(TimeOut) == 0) { System.out.println("獨自等待."); continue; }*/ // 取得迭代器.selectedKeys()中包含了每個準備好某一I/O操作的通道的SelectionKey Set<SelectionKey> set = selector.selectedKeys(); //輸出為1 //System.out.println("selectedKeysSize:" + set.size()); Iterator<SelectionKey> keyIter = set.iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); try { if (key.isAcceptable()) { System.out.println("acceptable"); //該方法在內部,會將interest由OP_ACCEPT改為OP_READ //如果不執行下面的語句,則會一直是accept狀態(初始時設定為了accept),無法進入後面的兩個if語句 //console一直列印上面的語句 protocol.handleAccept(key); } if (key.isReadable()) { // 從客戶端讀取資料 System.out.println("readable"); protocol.handleRead(key); } if (key.isValid() && key.isWritable()) { //客戶端連線一次後,N次連續進入該方法 //System.out.println("writable");//連續輸出 protocol.handleWrite(key); } } catch (IOException ex) { // 出現IO異常(如客戶端斷開連線)時移除處理過的鍵 keyIter.remove(); continue; } // 移除處理過的鍵 keyIter.remove(); } } } }
TCPProtocol介面:
package com.gw.demo; import java.io.IOException; import java.nio.channels.SelectionKey; 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; }
TCPProtocolImpl實現類:
package com.gw.demo; 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.text.SimpleDateFormat; import java.util.Date; 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); SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); String f = format.format(new Date()); // 準備傳送的文字 String sendString = "你好,客戶端. @" + f + ",已經收到你的資訊:" + 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 } }
TCPClient類:
package com.gw.demo;
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;
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"));
int r = socketChannel.write(writeBuffer);
System.out.println("write return:" + r);
//socketChannel.
}
public static void main(String[] args) throws IOException {
TCPClient client = new TCPClient("10.10.24.67", 1978);
for(int i=0; i<10; i++){
client.sendMsg("Nio" + i);
/*try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
}
TCPClientReadThread類:
package com.gw.demo;
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();
}
@Override
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();
}
}
}
服務端輸出如下:
獨自等待.
獨自等待.
acceptable
readable
接收到來自/10.10.24.67:57863的資訊:Nio0Nio1Nio2Nio3Nio4Nio5Nio6
readable
接收到來自/10.10.24.67:57863的資訊:Nio7Nio8Nio9
客戶端輸出如下:
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-18-23 15:18:06,已經收到你的資訊:Nio0Nio1Nio2Nio3Nio4Nio5Nio6你好,客戶端. @2015-18-23 15:18:06,已經收到你的資訊:Nio7Nio8Nio9
說明:客戶端迴圈十次,呼叫sendMsg,但是伺服器端只接收到了兩次訊息(不固定,多次執行,甚至只會接收到一次訊息),客戶端只收到了一次訊息。這是為什麼呢?
在client的買方法中,增加Thread.sleep(20);語句後。
服務端輸出如下:
獨自等待.
acceptable
readable
接收到來自/10.10.24.67:58343的資訊:Nio0
readable
接收到來自/10.10.24.67:58343的資訊:Nio1
readable
接收到來自/10.10.24.67:58343的資訊:Nio2
readable
接收到來自/10.10.24.67:58343的資訊:Nio3
readable
接收到來自/10.10.24.67:58343的資訊:Nio4
readable
接收到來自/10.10.24.67:58343的資訊:Nio5
readable
接收到來自/10.10.24.67:58343的資訊:Nio6
readable
接收到來自/10.10.24.67:58343的資訊:Nio7
readable
接收到來自/10.10.24.67:58343的資訊:Nio8
readable
接收到來自/10.10.24.67:58343的資訊:Nio9
客戶端輸出如下:
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio0你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio1
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio2
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio3
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio4
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio5
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio6
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio7
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio8
write return:10
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-31-23 15:31:56,已經收到你的資訊:Nio9
將TCPClient類的main方法改成如下形式:
public static void main(String[] args) throws IOException {
class MyThread extends Thread{
int i;
TCPClient client ;
public MyThread(TCPClient client, int index) {
i = index;
this.client = client;
}
@Override
public void run() {
try {
client.sendMsg("Nio" + i);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
TCPClient client = new TCPClient("10.10.24.67", 1978);
for(int i=0; i<10; i++){
new MyThread(client, i).start();
}
}
伺服器端輸出如下:
獨自等待.
acceptable
readable
接收到來自/10.10.24.67:58503的資訊:Nio1
readable
接收到來自/10.10.24.67:58503的資訊:Nio0Nio3Nio2Nio4Nio6Nio8Nio5Nio7Nio9
客戶端輸出如下:
接收到來自伺服器/10.10.24.67:1978的資訊:你好,客戶端. @2015-38-23 15:38:52,已經收到你的資訊:Nio1你好,客戶端. @2015-38-23 15:38:52,已經收到你的資訊:Nio0Nio3Nio2Nio4Nio6Nio8Nio5Nio7Nio9