經過上面步驟後
程序清單
public class NServer
{
//用於檢測所有Channel狀態的Selector
private Selector selector = null;
//定義實現編碼
private Charset charset = Charset
public void init()throws IOException
{
selector = Selector
//通過open方法來打開一個未綁定的ServerSocketChannel實例
ServerSocketChannel server = ServerSocketChannel
InetSocketAddress isa = new InetSocketAddress(
//將該ServerSocketChannel綁定到指定IP地址
server
//設置ServerSocket以非阻塞方式工作
server
//將server注冊到指定Selector對象
server
while (selector
{
//依次處理selector上的每個已選擇的SelectionKey
for (SelectionKey sk : selector
{
//從selector上的已選擇Key集中刪除正在處理的SelectionKey
selector
//如果sk對應的通道包含客戶端的連接請求
if (sk
{
//調用accept方法接受連接
SocketChannel sc = server
//設置采用非阻塞模式
sc
//將該SocketChannel也注冊到selector
sc
//將sk對應的Channel設置成准備接受其他請求
sk
}
//如果sk對應的通道有數據需要讀取
if (sk
{
//獲取該SelectionKey對應的Channel
SocketChannel sc = (SocketChannel)sk
//定義准備執行讀取數據的ByteBuffer
ByteBuffer buff = ByteBuffer
String content =
//開始讀取數據
try
{
while(sc
{
buff
content += charset
}
//打印從該sk對應的Channel裡讀取到的數據
System
//將sk對應的Channel設置成准備下一次讀取
sk
}
//如果捕捉到該sk對應的Channel出現了異常
//對應的Client出現了問題
catch (IOException ex)
{
//從Selector中刪除指定的SelectionKey
sk
if (sk
{
sk
}
}
//如果content的長度大於
if (content
{
//遍歷該selector裡注冊的所有SelectKey
for (SelectionKey key : selector
{
//獲取該key對應的Channel
Channel targetChannel = key
//如果該channel是SocketChannel對象
if (targetChannel instanceof SocketChannel)
{
//將讀到的內容寫入該Channel中
SocketChannel dest = (SocketChannel)targetChannel;
dest
}
}
}
}
}
}
}
public static void main(String[] args)
throws IOException
{
new NServer()
}
}
上面程序啟動時即建立一個可監聽連接請求的ServerSocketChannel
開始處理指定SelectionKey之後立即從該Selector中的被選擇的SelectionKey集合中刪除該SelectionKey
[
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27261.html