这里有一个小例子来开始使用NIO。
它是一个服务器,侦听端口80和81,并打印标准输出上收到的所有内容。在收到以 ; 开头的数据包后,连接被关闭整个服务器在收到以 开头的数据包后关闭。缺少发送部分和错误处理可能会更好一些。:-)CLOSE
QUIT
public static void main() throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
Selector selector = Selector.open();
ServerSocketChannel server1 = ServerSocketChannel.open();
server1.configureBlocking(false);
server1.socket().bind(new InetSocketAddress(80));
server1.register(selector, OP_ACCEPT);
ServerSocketChannel server2 = ServerSocketChannel.open();
server2.configureBlocking(false);
server2.socket().bind(new InetSocketAddress(81));
server2.register(selector, OP_ACCEPT);
while (true) {
selector.select();
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SocketChannel client;
SelectionKey key = iter.next();
iter.remove();
switch (key.readyOps()) {
case OP_ACCEPT:
client = ((ServerSocketChannel) key.channel()).accept();
client.configureBlocking(false);
client.register(selector, OP_READ);
break;
case OP_READ:
client = (SocketChannel) key.channel();
buffer.clear();
if (client.read(buffer) != -1) {
buffer.flip();
String line = new String(buffer.array(), buffer.position(), buffer.remaining());
System.out.println(line);
if (line.startsWith("CLOSE")) {
client.close();
} else if (line.startsWith("QUIT")) {
for (SelectionKey k : selector.keys()) {
k.cancel();
k.channel().close();
}
selector.close();
return;
}
} else {
key.cancel();
}
break;
default:
System.out.println("unhandled " + key.readyOps());
break;
}
}
}
}
Obs:(...) 的字段是静态导入的:SelectionKey
OP_ACCEPT
import static java.nio.channels.SelectionKey.*;