标签:
Java NIO提供了与标准IO不同的IO工作方式:
1. Channel的实现
Java NIO中最重要的通道的实现:
2. Buffer的类型
Java NIO 有以下Buffer类型:
2. Selector(选择器)
Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接。
Selector监听Channel时间类型:
eg:
监听端口888得到的数据
ServerSocketChannel serverSocketChannel1 = ServerSocketChannel.open();
serverSocketChannel1.socket().bind(new InetSocketAddress(888)); // 监听888端口
SocketChannel channel = serverSocketChannel.accept();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
Selector selector = Selector.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_ACCEPT); // socket接收
socketChannel.register(selector, SelectionKey.OP_READ); // 读
while(true) {
int readyChannels = selector.select();
if(readyChannels == 0) continue;
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
ServerSocketChannel serverSocketChannel = SelectionKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer buf = ByteBuffer.allocate(48);
socketChannel.read(buf);
} 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()) {
SocketChannel socketChannel = SelectionKey.channel();
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip(); // 将Buffer从写模式切换到读模式
socketChannel.write(buf);
// a channel is ready for writing
}
keyIterator.remove();
}
}
参考:http://www.iteye.com/magazines/132-Java-NIO#590
标签:
原文地址:http://www.cnblogs.com/hyiam/p/5920774.html