1、Netty简介Netty是由JBOSS提供的一个java开源网络通讯框架。Netty是基于Java NIO client-server的网络应用框架使用Netty可以快速开发网络应用例如服务器和客户端协议。Netty提供了一种新的方式来开发网络应用程序这种新的方式使它很容易使用和具有很强的扩展性。Netty的内部实现是很复杂的但是Netty提供了简单易用的API从网络处理代码中解耦业务逻辑。Netty是完全基于NIO实现的所以整个Netty都是异步的。netty的优点它的健壮性、功能、性能、可定制性和可扩展性在同类框架都是首屈一指的。它已经得到成百上千的商业/商用项目验证如Hadoop的RPC框架Avro、RocketMQ以及主流的分布式通信框架Dubbox等等。2、Hello World 入门2.1、Netty通信的步骤①创建两个NIO线程组一个专门用于网络事件处理接受客户端的连接另一个则进行网络通信的读写。②创建一个ServerBootstrap对象配置Netty的一系列参数例如接受传出数据的缓存大小等。③创建一个用于实际处理数据的类ChannelInitializer进行初始化的准备工作比如设置接受传出数据的字符集、格式以及实际处理数据的接口。④绑定端口执行同步阻塞方法等待服务器端启动即可。2.2、导入netty依赖注意版本dependency groupIdio.netty/groupId artifactIdnetty-all/artifactId version4.1.132.Final/version /dependency2.3、 代码实现2.3.1、 服务器端package com.xyq.netty.hello; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class Server { public static void main(String[] args) { EventLoopGroup bossLoopGroup new NioEventLoopGroup(); EventLoopGroup workerLoopGroup new NioEventLoopGroup(); // 服务端的启动对象 ServerBootstrap serverBootstrap new ServerBootstrap(); serverBootstrap.group(bossLoopGroup, workerLoopGroup) .channel(NioServerSocketChannel.class) // 声明通道类型 .option(ChannelOption.SO_BACKLOG, 1024)//设置tcp缓冲区 .option(ChannelOption.SO_RCVBUF, 32 * 1024)//设置接收缓冲大小 .childHandler(new ChannelInitializerSocketChannel() { Override protected void initChannel(SocketChannel socketChannel) throws Exception { // 通道(socketChannel)代表的是 连接的角色 管道(pipeline)代表的是 处理业务的逻辑管理 // 管道相当与一个链表 将不同的处理器连接起来管理的是处理器的顺序 socketChannel.pipeline().addLast(new NettyServerHandler()); } }); try { ChannelFuture channelFuture serverBootstrap.bind(8765).sync(); System.out.println(server start ...); // 此处会阻塞确保服务端一直是运行状态 channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { // 优雅关闭 bossLoopGroup.shutdownGracefully(); workerLoopGroup.shutdownGracefully(); } } }2.3.2、服务器管理类package com.xyq.netty.hello; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class NettyServerHandler extends ChannelInboundHandlerAdapter { /** * 通道可读时触发 * * param ctx 上下文 * param msg 消息 * throws Exception */ Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf (ByteBuf) msg; byte[] bytes new byte[buf.readableBytes()]; buf.readBytes(bytes); String msgStr new String(bytes, CharsetUtil.UTF_8); System.out.println(客户端消息: msgStr); } /** * 频道已读完毕 * * param ctx 上下文 * throws Exception */ Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer(hello client , CharsetUtil.UTF_8)); } /** * 发现异常 * * param ctx 上下文 * param cause * throws Exception */ Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); }2.3.3、 客户端package com.xyq.netty.hello; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; public class Client { public static void main(String[] args) { // 客户端事件循环组 只需要一个 EventLoopGroup group new NioEventLoopGroup(); // 客户端启动器 Bootstrap bootstrap new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializerSocketChannel() { Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler()); } }); try { ChannelFuture channelFuture bootstrap.connect(localhost, 8765).sync(); System.out.println(Client connect....); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { group.shutdownGracefully(); } } }2.3.4、客户端管理类package com.xyq.netty.hello; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; public class NettyClientHandler extends ChannelInboundHandlerAdapter { /** * 通道被启用 刚刚建立连接 的时候触发 * * param ctx CTX * throws Exception 例外情况 */ Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer(你好服务端,我是客户端, CharsetUtil.UTF_8)); } Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf (ByteBuf) msg; System.out.println(buf.readableBytes() buf.readableBytes()); byte[] bytes new byte[buf.readableBytes()]; buf.readBytes(bytes); String msgStr new String(bytes, CharsetUtil.UTF_8); System.out.println(服务端消息 msgStr); } Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { super.channelReadComplete(ctx); } Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
Netty入门(hello world)
发布时间:2026/5/26 6:07:59
1、Netty简介Netty是由JBOSS提供的一个java开源网络通讯框架。Netty是基于Java NIO client-server的网络应用框架使用Netty可以快速开发网络应用例如服务器和客户端协议。Netty提供了一种新的方式来开发网络应用程序这种新的方式使它很容易使用和具有很强的扩展性。Netty的内部实现是很复杂的但是Netty提供了简单易用的API从网络处理代码中解耦业务逻辑。Netty是完全基于NIO实现的所以整个Netty都是异步的。netty的优点它的健壮性、功能、性能、可定制性和可扩展性在同类框架都是首屈一指的。它已经得到成百上千的商业/商用项目验证如Hadoop的RPC框架Avro、RocketMQ以及主流的分布式通信框架Dubbox等等。2、Hello World 入门2.1、Netty通信的步骤①创建两个NIO线程组一个专门用于网络事件处理接受客户端的连接另一个则进行网络通信的读写。②创建一个ServerBootstrap对象配置Netty的一系列参数例如接受传出数据的缓存大小等。③创建一个用于实际处理数据的类ChannelInitializer进行初始化的准备工作比如设置接受传出数据的字符集、格式以及实际处理数据的接口。④绑定端口执行同步阻塞方法等待服务器端启动即可。2.2、导入netty依赖注意版本dependency groupIdio.netty/groupId artifactIdnetty-all/artifactId version4.1.132.Final/version /dependency2.3、 代码实现2.3.1、 服务器端package com.xyq.netty.hello; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class Server { public static void main(String[] args) { EventLoopGroup bossLoopGroup new NioEventLoopGroup(); EventLoopGroup workerLoopGroup new NioEventLoopGroup(); // 服务端的启动对象 ServerBootstrap serverBootstrap new ServerBootstrap(); serverBootstrap.group(bossLoopGroup, workerLoopGroup) .channel(NioServerSocketChannel.class) // 声明通道类型 .option(ChannelOption.SO_BACKLOG, 1024)//设置tcp缓冲区 .option(ChannelOption.SO_RCVBUF, 32 * 1024)//设置接收缓冲大小 .childHandler(new ChannelInitializerSocketChannel() { Override protected void initChannel(SocketChannel socketChannel) throws Exception { // 通道(socketChannel)代表的是 连接的角色 管道(pipeline)代表的是 处理业务的逻辑管理 // 管道相当与一个链表 将不同的处理器连接起来管理的是处理器的顺序 socketChannel.pipeline().addLast(new NettyServerHandler()); } }); try { ChannelFuture channelFuture serverBootstrap.bind(8765).sync(); System.out.println(server start ...); // 此处会阻塞确保服务端一直是运行状态 channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { // 优雅关闭 bossLoopGroup.shutdownGracefully(); workerLoopGroup.shutdownGracefully(); } } }2.3.2、服务器管理类package com.xyq.netty.hello; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class NettyServerHandler extends ChannelInboundHandlerAdapter { /** * 通道可读时触发 * * param ctx 上下文 * param msg 消息 * throws Exception */ Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf (ByteBuf) msg; byte[] bytes new byte[buf.readableBytes()]; buf.readBytes(bytes); String msgStr new String(bytes, CharsetUtil.UTF_8); System.out.println(客户端消息: msgStr); } /** * 频道已读完毕 * * param ctx 上下文 * throws Exception */ Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer(hello client , CharsetUtil.UTF_8)); } /** * 发现异常 * * param ctx 上下文 * param cause * throws Exception */ Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); }2.3.3、 客户端package com.xyq.netty.hello; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; public class Client { public static void main(String[] args) { // 客户端事件循环组 只需要一个 EventLoopGroup group new NioEventLoopGroup(); // 客户端启动器 Bootstrap bootstrap new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializerSocketChannel() { Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler()); } }); try { ChannelFuture channelFuture bootstrap.connect(localhost, 8765).sync(); System.out.println(Client connect....); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { group.shutdownGracefully(); } } }2.3.4、客户端管理类package com.xyq.netty.hello; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; public class NettyClientHandler extends ChannelInboundHandlerAdapter { /** * 通道被启用 刚刚建立连接 的时候触发 * * param ctx CTX * throws Exception 例外情况 */ Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer(你好服务端,我是客户端, CharsetUtil.UTF_8)); } Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf (ByteBuf) msg; System.out.println(buf.readableBytes() buf.readableBytes()); byte[] bytes new byte[buf.readableBytes()]; buf.readBytes(bytes); String msgStr new String(bytes, CharsetUtil.UTF_8); System.out.println(服务端消息 msgStr); } Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { super.channelReadComplete(ctx); } Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }