NIO是新IO,与老IO相比,老IO是通过STREAM来发送CHARACTER,新IO是通过CHANNL 发送BUFFER;老IO对于多条链接需要启动多个线程处理,新IO只需一条线程即可处理多条链接;新IO是事件驱动。
客户端,非SELECTOR模式:
//打开一个CHANNEL
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(
false);
socketChannel.connect(
new InetSocketAddress("http://google.com", 80));
//等待可写状态
while(! socketChannel.finishConnect() ){
//wait, or do something else
}
//写资料
socketChannel.write(buf);
客户端,SELECTOR模式:
//打开一个CHANNEL
SocketChannel channel = SocketChannel.open();
//新建一个SELECTOR
Selector selector = Selector.open();
channel.configureBlocking(false);
//将SELECTOR注册到CHANNEL中
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
while(true) {
//查询可用状态
int readyChannels = selector.select();
//状态不可用
if(readyChannels == 0) continue;
}
//状态可用
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
//提交所需处理的代码
}
//移除所有KEY
keyIterator.remove();
}