NIO selector使用的例子
时间: 2024-05-13 16:17:13 浏览: 82
NIO selector 是 Java NIO (New IO) 中的一个重要概念,它主要用于监听多个通道 (Channel) 上的 IO 事件。下面是一个简单的 NIO selector 的例子:
```
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NioServer {
public static void main(String[] args) throws IOException {
// 创建 ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress(8080));
// 创建 selector
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = socketChannel.read(buffer);
if (read > 0) {
buffer.flip();
System.out.println(new String(buffer.array(), 0, read));
}
}
iterator.remove();
}
}
}
}
```
在这个例子中,我们创建了一个 `ServerSocketChannel` 并绑定到端口 8080,然后创建了一个 selector 并将 serverSocketChannel 注册到 selector 上,监听 `OP_ACCEPT` 事件。当 selector 检测到有新的连接请求时,它会创建一个 `SocketChannel` 并将其注册到 selector 上,监听 `OP_READ` 事件。当 selector 检测到有数据可读时,它会读取客户端发送的数据
阅读全文