Netty学习-使用LineBasedFrameDecoder对粘包的处理

解决粘包问题的示例

package timeserver;

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;

public class TimeServer {
	
	public void bind(int port) throws Exception {
		
		//NioEventLoopGroup 是个线程组,它包含了一组NIO线程组,专门用于网络事件的处理,实际上它们是Reactor线程组。
		//两个线程组一个用于服务端接收客户端的连接,另一个用于进行SocketChannel的网络读写
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			//启动NIO服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new ChildChannelHandler());
			
			//启动辅助类配置完成之后,调用bind方法绑定监听端口,调用sync同步阻塞方法等待绑定操作完成
			ChannelFuture f = b.bind(port).sync();
			
			//阻塞,等待服务端链路关闭之后main函数才退出
			f.channel().closeFuture().sync();
			
			
		} finally {
			//线程组退出,释放资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
		
	}
	
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
		    //LineBasedFrameDecoder把换行符作为报文的分隔符,避免粘包
			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 = 8081;

		new TimeServer().bind(port);
	}
	
}

package timeserver;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeServerHandler extends ChannelHandlerAdapter {
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//对msg进行强制类型转换,ByteBuf的readableBytes方法可以获取缓冲区可读的字节数,
		//根据可读的字节数创建byte数组,通过ByteBuf的readBytes方法将缓冲区中的字节数组复制到新建的bytes数组中。
    	String body = (String)msg;
    	System.out.printf("THE TIME SERVER RECEIVE ORDER %s ", body);
		System.out.println("");
	
		SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
		String currentTime = "QUERY TIME ORDER".equals(body) ? f.format(new Date()) : "BAD QUERY ORDER";
		
		//把字符串构造成ByteBuf对象
		ByteBuf resp = Unpooled.copiedBuffer((currentTime + System.getProperty("line.separator")).getBytes());
		//发送应答消息,不把消息写入SocketChannel中,调用write方法只是把待发送的消息放到发送缓冲数组中
		ctx.write(resp);
	}
	
	
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //flush将缓冲区中的消息全部写入到SocketChannel中
    	ctx.flush();
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //释放资源
    	cause.printStackTrace();
    	ctx.close();
    }
}


package timeserver;

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;

public class TimeClient {
	
	public void connect(int port, String host) throws Exception {
		
		//客户端I/O读写的线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			//辅助启动类
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				
				//内部类初始化Channel,设置handler
				@Override
				protected 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();
		} finally {
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8081;
		new TimeClient().connect(port, "127.0.0.1");
	}

}

package timeserver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeClientHandler extends ChannelHandlerAdapter {
	
	
	private int count = 0;
	
	public TimeClientHandler() {
		
	}
	
	//收到服务端的应答消息之后ChannelRead方法被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	String body = (String)msg;
    	System.out.println("Now is : " + body + "; count is " + ++count);
    }
	
    //当客户端和服务端TCP链路建立成功之后, Netty的NIO线程会调用channelActive方法,发送消息给服务端
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	for (int i = 0 ; i < 100; i++) {
    	    //发送出去的消息使用换行符作为分隔符号
    		byte[] req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
    		ByteBuf firstMessage = Unpooled.buffer(req.length);
    		firstMessage.writeBytes(req);
            ctx.writeAndFlush(firstMessage);    		
    	}

    }

  
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    	cause.printStackTrace();
        ctx.close();
    }
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值