最近在项目中在做数据交换项目,用到netty框架,搭建框架都是从网上东扒一块,西一块下来凑合用,遇到问题了就百度解决,现在抽点时间从头开始学习!主要是根据《netty实战》进行入门的,案例来自本书;建议感兴趣的读者可以去看看,博主比较懒,代码就不改了,只是想研究原理,实战验证程序就可以!
1.建立服务端ChannelHandler 和业务逻辑
/** * @PackageName:com.netty.obj.handler * Description ChannelHandler 和业务逻辑 * @author: * @date:2021/12/21 */ /** * 标示一个ChannelHandler 可以被多个 Channel 安全地 共享 */ @ChannelHandler.Sharable public class EchoServerHandler extends ChannelInboundHandlerAdapter { /** * 对于每个传入的消息都要调用; * @param ctx * @param msg */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf in = (ByteBuf) msg; System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8)); ctx.write(in); } /** * 通知ChannelInboundHandler最后一次对channelRead()的调用是当前批量读取中的最后一条消息; * @param ctx */ @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } /** * 在读取操作期间,有异常抛出时会调用。 * @param ctx * @param cause */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
2.建立引导服务器
** * @PackageName:com.netty.obj.firstnetty * Description 引导服务器 * @author: * @date:2021/12/21 */ public class EchoServer { private final int port; public EchoServer(int port) { this.port = port; } public static void main(String[] args) throws Exception { int port = Integer.parseInt("9090"); //调用服务器的 start()方法 new EchoServer(port).start(); } public void start() throws Exception { final EchoServerHandler serverHandler = new EchoServerHandler(); //1.创建EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { //2.创建ServerBootstrap ServerBootstrap b = new ServerBootstrap(); b.group(group) //3.指定所使用的 NIO传输 Channel .channel(NioServerSocketChannel.class) //4.使用指定的端口设置套接字地址 .localAddress(new InetSocketAddress(port)) //5.添加一个EchoServerHandler 到子Channel的 ChannelPipeline .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { //EchoServerHandler 被标注为@Shareable,所以我们可以总是使用同样的实例 ch.pipeline().addLast(serverHandler); } }); //6.异步地绑定服务器;调用 sync()方法阻塞等待直到绑定完成 ChannelFuture f = b.bind().sync(); //7.获取 Channel 的CloseFuture,并且阻塞当前线程直到它完成 f.channel().closeFuture().sync(); } finally { //8.关闭 EventLoopGroup,释放所有的资源 group.shutdownGracefully().sync(); } } }
3.建立客户端ChannelHandler 和业务逻辑
/** * 标示一个ChannelHandler 可以被多个 Channel 安全地 共享 */ @ChannelHandler.Sharable public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { /** * 在到服务器的连接已经建立之后将被调用; * @param ctx */ @Override public void channelActive(ChannelHandlerContext ctx) { //当被通知 Channel是活跃的时候,发送一条消息 ctx.writeAndFlush(Unpooled.copiedBuffer("my first netty message!", CharsetUtil.UTF_8)); } /** * 当从服务器接收到一条消息时被调用; * @param ctx * @param in */ @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) { System.out.println( "Client received: " + in.toString(CharsetUtil.UTF_8)); } /** * 在处理过程中引发异常时被调用。 * @param ctx * @param cause */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
5.建立引导客户端
/** * @PackageName:com.netty.obj.firstnetty Description 引导客户端 * @author: * @date:2021/12/21 */ public class EchoClient { private final String host; private final int port; public EchoClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { //1.创建EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { //2.创建 Bootstrap Bootstrap b = new Bootstrap(); //指定 EventLoopGroup 以处理客户端事件;需要适用于 NIO 的实现 b.group(group) //适用于 NIO 传输的Channel 类型 .channel(NioSocketChannel.class) //设置服务器InetSocketAddress .remoteAddress(new InetSocketAddress(host, port)) //在创建Channel时,向 ChannelPipeline中添加一个 EchoClientHandler 实例 .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new EchoClientHandler()); } }); //连接到远程节点,阻塞等待直到连接完成 ChannelFuture f = b.connect().sync(); //阻塞,直到Channel 关闭 f.channel().closeFuture().sync(); } finally { //关闭线程池并且释放所有的资源 group.shutdownGracefully().sync(); } } public static void main(String[] args) throws Exception { String host = "127.0.0.1"; int port = Integer.parseInt("9090"); new EchoClient(host, port).start(); } }
6.maven依赖
<!--netty依赖--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.20.Final</version> </dependency>
7.启动服务端,启动客户端验证