Netty学习之TCP粘包/拆包

一.TCP粘包/拆包问题说明,如图





二.未考虑TCP粘包导致功能异常案例


    按照设计初衷,服务端应该收到100条查询时间指令的请求查询,客户端应该打印100次服务端的系统时间

1.服务端类

package com.phei.netty.s2016042302;

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;
/**
 * 服务端
 * @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)
      	 .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 {
			
			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.s2016042302;

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 {
		
		ByteBuf buf = (ByteBuf)msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req,"UTF-8").substring(0,req.length-System.getProperty("line.separator").length());
		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.s2016042302;

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;

/**
 * 客服端
 * @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{
					
					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.s2016042302;

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"+System.getProperty("line.separator")).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 {
		

		ByteBuf buf = (ByteBuf)msg;
		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);
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		
		//释放资源
		ctx.close();
	}

	 
}

5.运行结果





三.利用LineBasedFrameDecoder+StringDecoder(换行符的方式)解决TCP粘包问题


1.服务端类


package com.phei.netty.s20160423;

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;
/**
 * 服务端
 * @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)
      	 .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粘包问题
			arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
			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.s20160423;

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.s20160423;

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;

/**
 * 客服端
 * @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粘包问题
					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();
			
		}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.s20160423;

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"+System.getProperty("line.separator")).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.运行结果,完美解决



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值