/**
*
*/
package Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
*
* @author Administrator
* @version
*/
public class NBTest {
/** Creates new NBTest */
public NBTest() {
}
public void startServer() throws Exception {
int channels = 0;
int nKeys = 0;
int currentSelector = 0;
// 使用Selector
Selector selector = Selector.open();
// 建立Channel 並綁定到9000端口
ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress(
InetAddress.getLocalHost(), 9000);
ssc.socket().bind(address);
// 使設定non-blocking的方式。
ssc.configureBlocking(false);
// 向Selector註冊Channel及我們有興趣的事件
SelectionKey s = ssc.register(selector, SelectionKey.OP_ACCEPT);
printKeyInfo(s);
while (true) // 不斷的輪詢
{
debug("NBTest: Starting select");
// Selector通過select方法通知我們我們感興趣的事件發生了。
nKeys = selector.select();
// 如果有我們註冊的事情發生了,它的傳回值就會大於0
if (nKeys > 0) {
debug("NBTest: Number of keys after select operation: " + nKeys);
// Selector傳回一組SelectionKeys
// 我們從這些key中的channel()方法中取得我們剛剛註冊的channel。
Set selectedKeys = selector.selectedKeys();
Iterator i = selectedKeys.iterator();
while (i.hasNext()) {
s = (SelectionKey) i.next();
printKeyInfo(s);
debug("NBTest: Nr Keys in selector: "
+ selector.keys().size());
// 一個key被處理完成後,就都被從就緒關鍵字(ready keys)列表中除去
i.remove();
if (s.isAcceptable()) {
// 從channel()中取得我們剛剛註冊的channel。
Socket socket = ((ServerSocketChannel) s.channel())
.accept().socket();
SocketChannel sc = socket.getChannel();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);
System.out.println(++channels);
} else {
debug("NBTest: Channel not acceptable");
}
}
} else {
debug("NBTest: Select finished without any keys.");
}
}
}
private static void debug(String s) {
System.out.println(s);
}
private static void printKeyInfo(SelectionKey sk) {
String s = new String();
s = "Att: " + (sk.attachment() == null ? "no" : "yes");
s += ", Read: " + sk.isReadable();
s += ", Acpt: " + sk.isAcceptable();
s += ", Cnct: " + sk.isConnectable();
s += ", Wrt: " + sk.isWritable();
s += ", Valid: " + sk.isValid();
s += ", Ops: " + sk.interestOps();
debug(s);
}
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
NBTest nbTest = new NBTest();
try {
nbTest.startServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java7 nio 例子
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.