基础知识
1.首先图解拆包/粘包问题出现的原因
假设现在客户端向服务器端发送数据,在某一时间段上客户端分别发送了D1和D2二个数据包给服务器,由于服务器一次读取到的字节数是不确定的,故存在以下5种情况。<喎�"/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPsfpv/Yxo7q3/s7xxve31rb+tM62wcihtb3By7b+uPa2wMGitcTK/b7dsPyjrLfWsfDKx0Qxus1EMiyyosO709DVs7D8us2y8LD8o6zI58/CzbyjujxiciAvPg0KPGltZyBhbHQ9"" src="/uploadfile/Collfiles/20160718/20160718100900785.png" title="\" />
情况2:服务器一次接收到二个数据包,D1和D2粘合在一起,被成为TCP粘包。如下图:
情况3:服务器分二次读取到了二个数据包,第一次读取到了完整的D1包和D2包的一部分,第二次读取到了D2包的剩余部分,这被成为TCP拆包。如下图:
情况4:服务器分二次读取到了二个数据包,第一次读取到了D1包的部分内容 ,第二次读取到了D1包剩余部分和完整的D2包,这被成为TCP拆包。如下图:
情况5:如果服务器的TCP接收滑窗非常小,而数据包D1和D2比较大,很可能发生服务器多次才能将D1和D2接收完成,期间发生多次拆包。
2.粘包问题的解决策略
由于底层无法理解上层的业务数据,所以在底层是无法保证数据包不被拆分和重组的,这个问题只能通过上层的应用协议栈设计来解决,根据业界的主流协议的解决规范,可以归纳如下方法:
1.消息定长(如:每个报文大小固定200个字节,如果不够空位补空格)
2.在包尾增加回车换行符进行分割(如:FTP协议)。
3.将消息分为消息头和消息体,消息头中包含表示消息总长度的字段,通常设计思路为消息头的第一个字段使用int32来表示消息的总长度。
4.更复杂的应用层协议。
介绍完了TCP粘包/拆包的基础知识,下面我们通个一个例子来看看如何使用Netty提供半包解码器来解决拆包/粘包问题
以上摘自http://www.2cto.com/kf/201607/528101.html
我这边给出相关的代码实例:
包分为:cn.sh.daniel.tcp.client -----Client(客户端)
-----ClientTcpHandler (处理handler)
cn.sh.daniel.tcp.server -----Server(服务端)
-----ServerTcpHandler(处理handler)
----Client
package cn.sh.daniel.tcp.client;
import io.netty.bootstrap.Bootstrap;
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;
public class Client {
public static void main(String[] args) {
EventLoopGroup LoopGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(LoopGroup)
.channel(NioSocketChannel.class)//指定使用的传输通道
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientTcpHandler());
}
})
.option(ChannelOption.SO_KEEPALIVE, true);
//绑定指定的端口,进行监听
ChannelFuture f = b.connect("127.0.0.1",5678).sync();
//发送数据
f.channel().writeAndFlush(Unpooled.copiedBuffer("aaa".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer("bbbbb".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer("ccccccc".getBytes()));
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
LoopGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
----ClientTcpHandler
package cn.sh.daniel.tcp.client; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class ClientTcpHandler extends ChannelHandlerAdapter{ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //((ByteBuf)msg).release(); ByteBuf buf = (ByteBuf)msg; byte [] data = new byte[buf.readableBytes()]; buf.readBytes(data); String request = new String(data,"UTF-8"); System.out.println("Client :"+request); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
-----Server
package cn.sh.daniel.tcp.server;
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;
public class Server {
public static void main(String[] args) {
//1:NioEventLoopGroup专门处理TCP协议的事件循环器
EventLoopGroup bossLoopGroup = new NioEventLoopGroup();//接收client的连接
EventLoopGroup workLoopGroup = new NioEventLoopGroup();//实际的处理任务
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossLoopGroup, workLoopGroup)
.channel(NioServerSocketChannel.class)//指定使用的传输通道
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ServerTcpHandler());
}
})
//TCP配置
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
//绑定指定的端口,进行监听
ChannelFuture f = b.bind(5678).sync();
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//释放资源
bossLoopGroup.shutdownGracefully().sync();
workLoopGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
-----ServerTcpHandler
package cn.sh.daniel.tcp.server;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class ServerTcpHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// ((ByteBuf)msg).release();
ByteBuf buf = (ByteBuf) msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
String request = new String(data, "UTF-8");
System.out.println("Server :" + request);
// 给Client返回信息
String response = "reback";
// 冲刷数据,在Server端调用write后netty会自动释放消息
ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()))
.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
启动main方法: 先启动server 再启动client发现结果如下:
会发现发送了三次消息,而服务端当做了一次消息进行接收.
- 使用分隔符来分割消息
指定一个字符串,添加到pipeline中,然后再依次执行
可以看到三次发送结果,server端成功接收到数据
- 消息定长,不够的空格补缺
client端修改代码为:
client端发送消息修改为:
运行程序看到结果为:
5个a全部接收到,9个c只接收到了5个,因为上面handler中定长为5个
在修改client发送消息:
在最后一个c后面加个空格凑到10个长度,再运行程序看到如下结果:
- 将消息分为消息头和消息体,消息头中包含表示消息总长度的字段,通常设计思路为消息头的第一个字段使用int32来表示消息的总长度。