Java 网络编程:NIO、Netty 与异步 IO
·
一、引言
传统的 Java BIO(Blocking I/O)模型在高并发场景下效率低下。NIO、Netty 与异步 IO 的出现,彻底改变了这一格局。
二、BIO vs NIO vs AIO
| 模型 | 特点 | 适用场景 |
|---|---|---|
| BIO | 阻塞式、每连接一线程 | 小规模连接 |
| NIO | 非阻塞、单线程多连接 | 中高并发 |
| AIO | 异步回调 | 极高并发 |
三、NIO 原理与示例
NIO 以 Channel、Buffer、Selector 为核心:
Selector selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
if (key.isAcceptable()) {
SocketChannel client = server.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(256);
int read = channel.read(buffer);
if (read > 0) {
System.out.println("接收数据:" + new String(buffer.array()).trim());
}
}
}
}
该示例展示了单线程管理多连接的能力。
四、Netty 框架
Netty 是对 NIO 的高层封装,提供高性能、低延迟的网络通信框架。
4.1 核心组件
| 组件 | 功能 |
|---|---|
| Channel | 网络连接抽象 |
| EventLoop | 事件循环线程 |
| Pipeline | 责任链式处理器 |
| ByteBuf | 高性能内存缓冲 |
4.2 示例代码
public class NettyServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("收到消息: " + msg);
ctx.writeAndFlush("Echo: " + msg);
}
});
}
});
ChannelFuture f = b.bind(8080).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
五、异步 IO(AIO)机制
Java 7 引入了 AsynchronousSocketChannel 实现真正异步 IO:
AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(8080));
server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel client, Void att) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
public void completed(Integer result, ByteBuffer buf) {
buf.flip();
System.out.println("接收: " + new String(buf.array()).trim());
}
public void failed(Throwable exc, ByteBuffer buf) {}
});
}
public void failed(Throwable exc, Void att) {}
});
六、总结
| 模型 | 并发模型 | 框架 | 优点 |
|---|---|---|---|
| NIO | 单线程多连接 | Netty | 高性能、低延迟 |
| AIO | 异步回调 | JDK 原生 | 简洁、现代 |
| BIO | 阻塞线程 | - | 简单但性能低 |
理解 NIO 与 Netty 的核心思想,是迈向高性能网络编程的必经之路。
更多推荐

所有评论(0)