一、什么是Echo服务和快速创建Netty项目
- 什么是Echo服务:就是一个应答服务(回显服务器),客户端发送什么数据,服务端就响应的对应的数据,是一个用于调试和检测的服务
- IDEA + Maven + jdk8 netty依赖包
- Maven地址: 点我前往
也可以用我的版本,我的版本是2022年7月
<!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.79.Final</version> </dependency>
二、Netty实战之Echo服务-服务端程序编写实战
EchoServer
package com.example.test05.demo.echo; import io.netty.bootstrap.ServerBootstrap; 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.NioServerSocketChannel; public class EchoServer { private int port; public EchoServer(int port) { this.port = port; } /** * 启动流程 */ public void run() throws InterruptedException { //配置服务端线程组 两个线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); System.out.println("Echo 服务器启动ing"); //绑定端口,同步等待成功 ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); //等待服务端监听端口关闭 channelFuture.channel().closeFuture().sync(); } finally { //优雅退出,释放线程池 workGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { int port = 8080; if (args.length > 0) { port = Integer.parseInt(args[0]); } new EchoServer(port).run(); } }
EchoServerHandler
package com.example.test05.demo.echo; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf data = (ByteBuf) msg; System.out.println("服务端收到数据: "+ data.toString(CharsetUtil.UTF_8)); ctx.writeAndFlush(data); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("EchoServerHandle channelReadComplete"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
三、Netty实战之Echo服务-客户端程序编写实战
EchoClient
package com.example.test05.demo.echo; import io.netty.bootstrap.Bootstrap; 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; import java.net.InetSocketAddress; public class EchoClient { private String host; private int port; public EchoClient(String host, int port) { this.host = host; this.port = port; } public void start() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); } }); //连接到服务端,connect是异步连接,在调用同步等待sync,等待连接成功 ChannelFuture channelFuture = bootstrap.connect().sync(); //阻塞直到客户端通道关闭 channelFuture.channel().closeFuture().sync(); } finally { //优雅退出,释放NIO线程组 group.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { new EchoClient("127.0.0.1", 8081).start(); } }
EchoClientHandler
package com.example.test05.demo.echo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.CharsetUtil; public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println("Client received: " + msg.toString(CharsetUtil.UTF_8)); } /** * 激活之后运行 * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Active"); // 申请一个内存 Unpooled.copiedBuffer ctx.writeAndFlush(Unpooled.copiedBuffer("DBC博客 www.dbc655.top",CharsetUtil.UTF_8)); } /** * 读取数据结束后 * @param ctx * @throws Exception */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("EchoClientHandler channelReadComplete"); } /** * 异常捕获的方法 * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
四、Netty实战之Echo服务演示和整个流程分析
简单的大话说明,详细请点击里面的文章
本文作者为DBC,转载请注明。