netty5.0通过LineBasedFrameDecoder和StringDecoder解决粘包
生活随笔
收集整理的這篇文章主要介紹了
netty5.0通过LineBasedFrameDecoder和StringDecoder解决粘包
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
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; import?io.netty.handler.codec.LineBasedFrameDecoder; import?io.netty.handler.codec.string.StringDecoder;/***?server?粘包問題通過LineBasedFrameDecoder、StringDecoder解決*?@author?**/ public?class?TimeServer?{public?void?bind(int?port)?{//?服務器線程組?用于網絡事件的處理?一個用于服務器接收客戶端的連接//?另一個線程組用于處理SocketChannel的網絡讀寫EventLoopGroup?bossGroup?=?new?NioEventLoopGroup();EventLoopGroup?workerGroup?=?new?NioEventLoopGroup();try?{//NIO服務器端的輔助啟動類?降低服務器開發難度ServerBootstrap?b?=?new?ServerBootstrap();b.group(bossGroup,?workerGroup).channel(NioServerSocketChannel.class)????//?類似NIO中serverSocketChannel.option(ChannelOption.SO_BACKLOG,?1024)???//?配置TCP參數.childHandler(new?ChildChannelHandler());?//?最后綁定I/O事件的處理類//?服務器啟動后?綁定監聽端口?同步等待成功?主要用于異步操作的通知回調?回調處理用的ChildChannelHandlerChannelFuture?f?=?b.bind(port).sync();System.out.println("The?time?Server?is?start?:?"+port);//?等待服務端監聽端口關閉f.channel().closeFuture().sync();}?catch?(InterruptedException?e)?{e.printStackTrace();}?finally{//?優雅退出?釋放線程池資源workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();System.out.println("服務器優雅的釋放了線程資源...");}}/***?網絡事件處理器*?@author**/private?class?ChildChannelHandler?extends?ChannelInitializer<SocketChannel>?{@Overrideprotected?void?initChannel(SocketChannel?ch)?throws?Exception?{ch.pipeline().addLast(new?LineBasedFrameDecoder(1024));ch.pipeline().addLast(new?StringDecoder());??//設置字符串解碼器?自動將報文轉為字符串ch.pipeline().addLast(new?TimeServerHandler());}}public?static?void?main(String[]?args)?{int?port?=?8080;if(null?!=?args?&&?args.length?>?0)?{try?{port?=?Integer.parseInt(args[0]);}?catch?(NumberFormatException?e)?{e.printStackTrace();}}new?TimeServer().bind(port);} } import?java.util.Date;import?io.netty.buffer.ByteBuf; import?io.netty.buffer.Unpooled; import?io.netty.channel.ChannelHandlerAdapter; import?io.netty.channel.ChannelHandlerContext;/***?server端網絡IO事件處理*?@author?**/ public?class?TimeServerHandler?extends?ChannelHandlerAdapter?{private?int?counter;@Overridepublic?void?channelRead(ChannelHandlerContext?ctx,?Object?msg)throws?Exception?{System.out.println("服務器讀取到客戶端請求...");String?body?=?(String)msg;System.out.println("The?time?server?receive?order?:"+body+";the?counter?is?"+?++counter);String?currentTime?=?"QUERY?TIME?ORDER".equalsIgnoreCase(body)???new?Date(System.currentTimeMillis()).toString()?:?"BAD?ORDER";currentTime?=?currentTime?+?System.getProperty("line.separator");ByteBuf?resp?=?Unpooled.copiedBuffer(currentTime.getBytes());ctx.writeAndFlush(resp);System.out.println("服務器做出了響應");}@Overridepublic?void?channelReadComplete(ChannelHandlerContext?ctx)?throws?Exception?{ctx.flush();System.out.println("服務器readComplete?響應完成");}@Overridepublic?void?exceptionCaught(ChannelHandlerContext?ctx,?Throwable?cause)throws?Exception?{ctx.close();System.out.println("服務器異常退出"+cause.getMessage());} } 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; import?io.netty.handler.codec.LineBasedFrameDecoder; import?io.netty.handler.codec.string.StringDecoder;/***?client?粘包問題通過LineBasedFrameDecoder、StringDecoder解決*?@author?**/ public?class?TimeClient?{/***?連接服務器*?@param?host*?@param?port*/public?void?connect(String?host,?int?port)?{//配置客戶端nio線程組EventLoopGroup?group?=?new?NioEventLoopGroup();try?{//客戶端輔助啟動類?對客戶端配置Bootstrap?b?=?new?Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,?true).handler(new?ChannelInitializer<SocketChannel>()?{@Overrideprotected?void?initChannel(SocketChannel?ch)?throws?Exception?{ch.pipeline().addLast(new?LineBasedFrameDecoder(1024));ch.pipeline().addLast(new?StringDecoder());ch.pipeline().addLast(new?TimeClientHandler());}});//異步鏈接服務器?同步等待鏈接成功ChannelFuture?f?=?b.connect(host,?port).sync();//等待鏈接關閉f.channel().closeFuture().sync();}?catch?(InterruptedException?e)?{e.printStackTrace();}?finally{group.shutdownGracefully();System.out.println("客戶端優雅的釋放了線程資源...");}}public?static?void?main(String[]?args)?{int?port?=?8080;if(null?!=?args?&&?args.length?>?0)?{try?{port?=?Integer.parseInt(args[0]);}?catch?(NumberFormatException?e)?{e.printStackTrace();}}new?TimeClient().connect("127.0.0.1",?port);} } import?io.netty.buffer.ByteBuf; import?io.netty.buffer.Unpooled; import?io.netty.channel.ChannelHandlerAdapter; import?io.netty.channel.ChannelHandlerContext;import?java.util.logging.Logger;/***?Client?網絡IO事件處理*?@author**/ public?class?TimeClientHandler?extends?ChannelHandlerAdapter?{private?static?final?Logger?logger?=?Logger.getLogger(TimeClientHandler.class.getName());private?int?counter;private?byte[]?req;public?TimeClientHandler()?{req?=?("QUERY?TIME?ORDER"?+?System.getProperty("line.separator")).getBytes();}@Overridepublic?void?channelActive(ChannelHandlerContext?ctx)?throws?Exception?{ByteBuf?message?=?null;for(int?i=0;?i<100;?i++)?{message?=?Unpooled.buffer(req.length);message.writeBytes(req);ctx.writeAndFlush(message);}logger.info("客戶端active");}@Overridepublic?void?channelRead(ChannelHandlerContext?ctx,?Object?msg)throws?Exception?{logger.info("客戶端收到服務器響應數據");String?body?=?(String)msg;System.out.println("Now?is?:?"+body+";?the?counter?is?:?"+?++counter);}@Overridepublic?void?exceptionCaught(ChannelHandlerContext?ctx,?Throwable?cause)throws?Exception?{logger.warning("Unexpected?exception?from?downstream:"+cause.getMessage());ctx.close();System.out.println("客戶端異常退出");}}轉載于:https://my.oschina.net/chaun/blog/391962
總結
以上是生活随笔為你收集整理的netty5.0通过LineBasedFrameDecoder和StringDecoder解决粘包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rhel6.5网卡初始化错误解决
- 下一篇: iOS NSOperation 非并发执