Netty学习之固定长度解码器解决TCP粘包
2016-04-24 16:32
579 查看
一.FixedLengthFrameDecoder
FixedLengthFrameDecoder是固定长度解码器,它能够按照指定长度的长度对消息进行自动解码,开发者不需要考虑TCP粘包/拆包问题,非常实用。二.FixedLengthFrameDecoder应用开发
1.服务器类
package com.phei.netty.s2016042401; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.DelimiterBasedFrameDecoder; import io.netty.handler.codec.FixedLengthFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * 服务端 * @author renhj * */ public class TimeServer { public void bind(int port) throws Exception{ //第一个用户服务器接收客户端的连接 EventLoopGroup bossGroup = new NioEventLoopGroup(); //第二个用户SocketChannel的网络读写 EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ //创建ServerBootstrap对象,启动 NIO服务端的辅助启动类 ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup). //设置为NIO channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChildChannelHandler()); //绑定端口,同步等待成功 ChannelFuture f = b.bind(port).sync(); //等待服务器监听端口关闭 f.channel().closeFuture().sync(); }finally{ //释放线程池资源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel arg0) throws Exception { //解决TCP粘包问题,设置固定长度16字节的解码器 arg0.pipeline().addLast(new FixedLengthFrameDecoder(16)); arg0.pipeline().addLast(new StringDecoder()); arg0.pipeline().addLast(new TimeServerHandler()); } } public static void main(String[] args) throws Exception { int port = 8080; if(args != null && args.length>0){ try{ port = Integer.valueOf(args[0]); }catch(Exception e){ //采用默认值 } } new TimeServer().bind(port); } }
2.服务器核心处理类
package com.phei.netty.s2016042401; import java.util.Date; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; /** * 服务端核心处理类 * @author renhj * */ public class TimeServerHandler extends ChannelHandlerAdapter { private int counter; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 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); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
3.客户端类
package com.phei.netty.s2016042401; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.DelimiterBasedFrameDecoder; import io.netty.handler.codec.FixedLengthFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * 客服端 * @author renhj * */ public class TimeClient { public void connect(int port , String host) throws Exception{ //配置客户端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>(){ @Override public void initChannel(SocketChannel ch) throws Exception{ //解决TCP粘包问题,设置固定长度30字节的解码器 ch.pipeline().addLast(new FixedLengthFrameDecoder(30)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeClientHandler()); } }); //发起异步连接操作 ChannelFuture f = b.connect(host, port).sync(); //等待客户端链路关闭 f.channel().closeFuture().sync(); }finally{ //释放NIO线程 group.shutdownGracefully(); } } public static void main(String[] args) throws Exception{ int port = 8080; if(args !=null && args.length>0){ try{ port = Integer.valueOf(args[0]); }catch(Exception e){ } } new TimeClient().connect(port, "127.0.0.1"); } }
4.客户端核心处理类
package com.phei.netty.s2016042401; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; /** * 客户端核心处理类 * @author renhj * */ public class TimeClientHandler extends ChannelHandlerAdapter { private int counter; private byte[] req; public TimeClientHandler(){ req = ("QUERY TIME ORDER").getBytes(); } @Override public 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); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String body = (String)msg; System.out.println("Now is : "+body +" ; the counter is : "+ ++counter); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { //释放资源 ctx.close(); } }
5.运行结果
相关文章推荐
- saltstack的安装(转载连接)
- yum扩展源(国内镜像站的修改)
- 网络参考模型: OSI参考模型;TCP/IP参考模型
- Netty学习之分隔符解决TCP粘包
- Apache主配置文件httpd.conf 详解
- HttpClient和HttpURLConnection的区别(by 星空武哥)
- 【菜鸟学安卓】- 获取网络图片二 BitmapFactory options OutOfMemery问题内存溢出
- httpd编译安装
- HttpClient4.2 Fluent API学习
- Android访问网络,使用HttpURLConnection还是HttpClient?
- 【菜鸟学安卓】- 获取网络图片一 BitmapFactory options OutOfMemery问题内存溢出
- 使用VMware虚拟机,分别部署2台centos7主机实现,httpd(php模块)+mysql,
- http-关于application/x-www-form-urlencoded等字符编码的解释说明
- 北京林业大学“计蒜客”杯程序设计竞赛 网络赛 G. 易彰彪的一张表 (KMP)
- web端 出报错 GET http://localhost/favicon.ico 500 (INTERNAL SERVER ERROR)
- JAVA IO-网络流
- 北京林业大学“计蒜客”杯程序设计竞赛 网络赛 B. 大钉骑马走江湖 (广搜)
- [heartbeat]基于httpclient的文件可配置的心跳检测应用
- Http协议学习总结
- iOS网络编程 - 5