Netty学习之分隔符解决TCP粘包

一.DelimiterBasedFrameDecoder解决TCP粘包


      根据自己的需求,制定特定的分割符作为特定的结束标志,这里以“$_”作为分隔符为例,解决TCP粘包问题。注意客户端和服务器发送一个包中的消息需要以“$_”作为结束符。


二.DelimiterBasedFrameDecoder应用开发


1.服务器类

package com.phei.netty.s20160424;

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.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粘包问题,以"$_"作为分隔
			ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
			arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
			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.s20160424;

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");
				currentTime = currentTime + "$_";	
	    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.s20160424;

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.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粘包问题,以"$_"作为分隔
					ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
					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.s20160424;

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.运行结果


Netty学习之分隔符解决TCP粘包_第1张图片 Netty学习之分隔符解决TCP粘包_第2张图片

你可能感兴趣的:(netty)