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