?? nserver.java
字號:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;
/**
* Description:
* <br/>Copyright (C), 2008-2010, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class NServer
{
//用于檢測所有Channel狀態的Selector
private Selector selector = null;
//定義實現編碼、解碼的字符集對象
private Charset charset = Charset.forName("UTF-8");
public void init()throws IOException
{
selector = Selector.open();
//通過open方法來打開一個未綁定的ServerSocketChannel實例
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress(
"127.0.0.1", 30000);
//將該ServerSocketChannel綁定到指定IP地址
server.socket().bind(isa);
//設置ServerSocket以非阻塞方式工作
server.configureBlocking(false);
//將server注冊到指定Selector對象
server.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0)
{
//依次處理selector上的每個已選擇的SelectionKey
for (SelectionKey sk : selector.selectedKeys())
{
//從selector上的已選擇Key集中刪除正在處理的SelectionKey
selector.selectedKeys().remove(sk);
//如果sk對應的通道包含客戶端的連接請求
if (sk.isAcceptable())
{
//調用accept方法接受連接,產生服務器端對應的SocketChannel
SocketChannel sc = server.accept();
//設置采用非阻塞模式
sc.configureBlocking(false);
//將該SocketChannel也注冊到selector
sc.register(selector, SelectionKey.OP_READ);
//將sk對應的Channel設置成準備接受其他請求
sk.interestOps(SelectionKey.OP_ACCEPT);
}
//如果sk對應的通道有數據需要讀取
if (sk.isReadable())
{
//獲取該SelectionKey對應的Channel,該Channel中有可讀的數據
SocketChannel sc = (SocketChannel)sk.channel();
//定義準備執行讀取數據的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
//開始讀取數據
try
{
while(sc.read(buff) > 0)
{
buff.flip();
content += charset.decode(buff);
}
//打印從該sk對應的Channel里讀取到的數據
System.out.println("=====" + content);
//將sk對應的Channel設置成準備下一次讀取
sk.interestOps(SelectionKey.OP_READ);
}
//如果捕捉到該sk對應的Channel出現了異常,即表明該Channel
//對應的Client出現了問題,所以從Selector中取消sk的注冊
catch (IOException ex)
{
//從Selector中刪除指定的SelectionKey
sk.cancel();
if (sk.channel() != null)
{
sk.channel().close();
}
}
//如果content的長度大于0,即聊天信息不為空
if (content.length() > 0)
{
//遍歷該selector里注冊的所有SelectKey
for (SelectionKey key : selector.keys())
{
//獲取該key對應的Channel
Channel targetChannel = key.channel();
//如果該channel是SocketChannel對象
if (targetChannel instanceof SocketChannel)
{
//將讀到的內容寫入該Channel中
SocketChannel dest = (SocketChannel)targetChannel;
dest.write(charset.encode(content));
}
}
}
}
}
}
}
public static void main(String[] args)
throws IOException
{
new NServer().init();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -