之前已经使用了LineBasedFrameDecoder解决TCP粘包问题,现在再学两种解决TCP粘包的方法。
- DelimiterBasedFrameDecoder:可以自动完成以分隔符做结束标志的消息的解码,分隔符自定义。
- FixedLengthFrameDecoder: 固定长度解码器,它能够按照指定的长度对消息进行自动解码,开发者不需要考虑TCP的粘包/拆包问题
DelimiterBasedFrameDecoder编码实践
与之前LineBaseFrameDecoder的使用一样,只要将DelimiterBasedFrameDecoder和StringDecoder添加到服务端和客户端的ChannelPipeline中。
服务端
package com.ph.Netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.string.StringDecoder;
/**
* Create by PH on 2018/11/6
*/
public class NettyServer {
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//采用默认值
}
}
new NettyServer().bind(port);
}
public void bind(int port) throws Exception{
//NioEventLoopGroup是一个线程组,包含了一组NIO线程,专门用于网络事件的处理,实际上他们就是Reactor线程组
//bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//用于进行SocketChannel的网络读写
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
ServerBootstrap b = new ServerBootstrap();
//配置NIO服务端
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel产生一个Channel用来接收连接,他的功能对应于JDK
// NIO类库中的ServerSocketChannel类。
.channel(NioServerSocketChannel.class)
//BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,
// 用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,
// Java将使用默认值50。
.option(ChannelOption.SO_BACKLOG, 1024)
//绑定I/O事件处理类,作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel arg0) throws Exception {
//定义分隔符为"#_"
ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
//添加分隔符解码器,第一个参数表示单条消息最大长度,第二个参数是分隔符缓冲对象
arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
arg0.pipeline().addLast(new StringDecoder());
arg0.pipeline().addLast(new ServerHandler());
}
});
//绑定端口,同步等待绑定操作完成,完成后返回一个ChannelFuture,用于异步操作的通知回调
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭之后才退出main函数
f.channel().closeFuture().sync();
} finally {
//退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
/**
* ChannelInboundHandlerAdapter实现自ChannelInboundHandler
* ChannelInboundHandler提供了不同的事件处理方法你可以重写
*/
class ServerHandler extends ChannelInboundHandlerAdapter {
private int count = 0;
/**
* 接受客户端发送的消息
* @param ctx
* @param msg
* @throws Exception
*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//拿到的msg已经是解码成字符串之后的应答消息了
String body = (String)msg;
++count;
System.out.println("Server receive: " + body + count);
//获得ByteBuf类型的数据
ByteBuf resp = Unpooled.copiedBuffer(("Server message #_").getBytes());
//向客户端发送消息,不直接将消息写入SocketChannel中,只是把待发送的消息放到发送缓存数组中,
//再通过调用flush方法将缓冲区中的消息全部写到SocketChannel中
ctx.write(resp);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将消息发送队列中的消息写入到SocketChannel中发送给对方
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//当发生异常时释放资源
ctx.close();
}
}
客户端
package com.ph.Netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.string.StringDecoder;
/**
* Create by PH on 2018/11/6
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
//采用默认值
}
}
new NettyClient().connect(port, "127.0.0.1");
}
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>() {
public void initChannel(SocketChannel ch) throws Exception{
//定义分隔符为"#_"
ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
//添加分隔符解码器,第一个参数表示单条消息最大长度,第二个参数是分隔符缓冲对象
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ClientHandler());
}
});
//发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
//等待客户端链路关闭
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
private ByteBuf msg;
private int count = 0;
private byte[] req;
public ClientHandler() {
req = ("Client message " + "#_").getBytes();
}
/**
* 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用此方法
* @param ctx
*/
public void channelActive(ChannelHandlerContext ctx) {
//发送消息到服务端
for (int i=0;i<10;i++) {
msg = Unpooled.buffer(req.length);
msg.writeBytes(req);
ctx.writeAndFlush(msg);
}
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
//StringDecoder已经将ByteBuf的消息转换成字符串,msg已经是解码成字符串之后的应答消息了。
String body = (String)msg;
System.out.println("Client receive :" + body + ", the counter is:" + String.valueOf(++count));
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}
在DelimiterBasedFrameDecoder的使用中,要注意的是在创建其对象时的参数,第一个参数表示单条消息的最大长度,当达到该长度后仍然没有查找到分隔符,就抛出TooLongFrameException异常,防止由于异常码流缺失分隔符号导致的内存溢出;第二个参数就是分隔符缓冲对象。
FixedlengthFrameDecoder编码实践
由于与之前代码类似,这里就贴一部分
protected void initChannel(SocketChannel arg0) throws Exception {
//定义分隔符为"#_"
//ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
//添加分隔符解码器
//arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
arg0.pipeline().addLast(new FixedLengthFrameDecoder(20));
arg0.pipeline().addLast(new StringDecoder());
arg0.pipeline().addLast(new ServerHandler());
}