1.业务处理服务端handler
/** * @PackageName:com.netty.obj.firstnetty Description * @author: * @date:2021/12/22 */ public class TimeServerHandler extends ChannelInboundHandlerAdapter { private int counter; /** * 对于每个传入的消息都要调用; * @param ctx * @param msg */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; byte[] req = new byte[in.readableBytes()]; in.readBytes(req); String body = new String(req,"UTF-8").substring(0,req.length-System.getProperty("line.separator").length()); System.out.println("Server received: " + body+";"+"the counter is :"+ ++counter); String currTime = "QUERY TIME ORDER".equalsIgnoreCase(body)? new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER"; currTime = currTime+System.getProperty("line.separator"); ByteBuf resp = Unpooled.copiedBuffer(currTime.getBytes()); ctx.write(resp); } /** * 通知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 TimeServerHandler serverHandler = new TimeServerHandler(); //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.业务处理客户端handler
/** * @PackageName:com.netty.obj.firstnetty Description * @author: * @date:2021/12/22 */ public class TimeClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private int counter; private byte[] req; public TimeClientHandler(){ req =( "QUERY TIME ORDER"+System.getProperty("line.separator")).getBytes(); } /** * 在到服务器的连接已经建立之后将被调用; * @param ctx */ @Override public void channelActive(ChannelHandlerContext ctx) { //当被通知 Channel是活跃的时候,发送一条消息 ByteBuf message = null; for (int i=0;i<100;i++){ message = Unpooled.buffer(req.length); message.writeBytes(req); ctx.writeAndFlush(message); } } /** * 当从服务器接收到一条消息时被调用; * @param ctx * @param in */ @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception{ ByteBuf buf = (ByteBuf)in; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req,"UTF-8"); System.out.println("NOW IS "+body+";" +"the counter is " + ++counter); 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(); } }
4.引导客户端
/** * @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 TimeClientHandler()); } }); //连接到远程节点,阻塞等待直到连接完成 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(); } }
5.启动服务端,客户端
服务端没有一次性接收到数据包
使用LineBasedFramDecode和StringDecode
使用DelimiterBasedFramDecode
使用fixedLengthFramDecode
解决粘包拆包问题