netty入门demo
参考博客:(14条消息) 【Netty整理01-快速入门】Netty简单使用Demo(已验证)_the_fool_的博客-CSDN博客
ServerHandler.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package com.hmb; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println( "server read...." ); ByteBuf buf = (ByteBuf) msg; byte [] date = new byte [buf.readableBytes()]; buf.readBytes(date); System.out.println( "client msg: " + new String(date)); buf.release(); System.out.println( "send msg to client..." ); String response = "hello client" ; ByteBuf buf1 = ctx.alloc().buffer(); buf1.writeBytes(response.getBytes()); ctx.write(buf1); ctx.flush(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } } |
NettyServer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package com.hmb; import io.netty.bootstrap.Bootstrap; 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 NettyServer { private int port = 9999 ; public void start() { EventLoopGroup worker = new NioEventLoopGroup(); EventLoopGroup boss = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker) .option(ChannelOption.SO_BACKLOG, 1024 ) .option(ChannelOption.SO_KEEPALIVE, true ) .channel(NioServerSocketChannel. class ) .childHandler( new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new ServerHandler()); } }); try { ChannelFuture cf = serverBootstrap.bind(port).sync(); cf.channel().closeFuture() .sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } public static void main(String[] args) { NettyServer server = new NettyServer(); server.start(); } } |
ClientHandler.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.hmb; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println( "read msg from server..." ); ByteBuf buf = (ByteBuf) msg; byte [] date = new byte [buf.readableBytes()]; buf.readBytes(date); System.out.println( "server msg: " + new String(date)); buf.release(); Thread.sleep( 10000 ); System.out.println( "send msg to server..." ); String response = "hello server" ; ByteBuf buf1 = ctx.alloc().buffer(); buf1.writeBytes(response.getBytes()); ctx.write(buf1); ctx.flush(); } /** * channel生命周期回调函数,channel准备好后回调此函数,不能少,否则bs交互无法发起 * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println( "firstly send msg to server..." ); String msg = "hello server!" ; ByteBuf encode = ctx.alloc().buffer( 4 * msg.length()); encode.writeBytes(msg.getBytes()); ctx.write(encode); ctx.flush(); } } |
NettyClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.hmb; import io.netty.bootstrap.Bootstrap; 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.NioSocketChannel; public class NettyClient { public void connect(String host, int port) { EventLoopGroup worker = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(worker) .channel(NioSocketChannel. class ) .option(ChannelOption.SO_KEEPALIVE, true ) .handler( new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new ClientHandler()); } }); try { ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { worker.shutdownGracefully(); } } public static void main(String[] args) { NettyClient nettyClient = new NettyClient(); nettyClient.connect( "127.0.0.1" , 9999 ); } } |
先运行NettyServer.java的main方法,再运行NettyClient.java的main方法,此时就可以看到bs的交互信息
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?