java I/O多路复用的场景及代码
时间: 2024-01-19 19:02:49 浏览: 109
Java NIO(New IO)支持I/O多路复用,它提供了Selectors类来实现多路复用。Selectors实际上是一个轮询器,它可以处理多个Channel的事件。
以下是Java NIO I/O多路复用的一个简单示例,它使用ServerSocketChannel和SocketChannel来实现一对多的通信:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class MultiplexingServer {
public static void main(String[] args) throws IOException {
// 创建ServerSocketChannel
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
// 绑定端口
InetSocketAddress address = new InetSocketAddress(9999);
serverChannel.bind(address);
// 创建Selector
Selector selector = Selector.open();
// 注册ServerSocketChannel到Selector
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 监听事件
int readyChannels = selector.select();
// 处理事件
if (readyChannels > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// 处理连接事件
if (key.isAcceptable()) {
ServerSocketChannel server = (
阅读全文