TCP 粘包和拆包基本介绍
1)TCP是面向连接的,面向流的,提供高可靠性服务。客户端和服务器端都要有一一相对的socket,因此,发送端为了将多个发送给接收端的包,更有效的发给对方,使用了优化方法,将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包,这样虽然提高了效率,但是接收端就难于分辨出完整的数据包了,因为面向流 的通信是无消息保护边界的。
解决方案
使用自定义协议+编解器来解决,关键就是要解决服务器端每次读取数据长度的问题,这个问题的解决就不会出现服务器多读或少读数据的问题,从而避免了TCP 的粘包、拆包。
示例
定义一个协议包
@Data
public class MessageProtocol {
private int len; //关键
private byte[] content;
}
实现服务器端
public class MyServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap boot = new ServerBootstrap();
boot.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new MyServerInitializer());//自定义一个初始化类
ChannelFuture channelFuture = boot.bind(7000).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class MyServerInitializer extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline=socketChannel.pipeline();
pipeline.addLast(new MyMessageDecoder());//解码器
pipeline.addLast(new MyMessageEncoder());
pipeline.addLast(new MyServerHandler());
}
}
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
private int count;
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("出现异常。。。");
cause.printStackTrace();
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
//接收到数据,并处理
int len=msg.getLen();
byte[] content=msg.getContent();
System.out.println("服务器接收到的信息如下");
System.out.println("长度="+len);
System.out.println("内容="+new String(content,Charset.forName("utf-8")));
System.out.println("服务器接收到的消息包数量="+(++this.count));
System.out.println("\n\n");
//回复消息
String responseContent=UUID.randomUUID().toString();
int responseLen=responseContent.getBytes("utf-8").length;
byte[] responseContent2=responseContent.getBytes("utf-8");
//构建一个协议包
MessageProtocol messageProtocol=new MessageProtocol();
messageProtocol.setLen(responseLen);
messageProtocol.setContent(responseContent2);
channelHandlerContext.writeAndFlush(messageProtocol);
System.out.println("回复消息发送\n");
}
}
自定义的编码、解码器
public class MyMessageEncoder extends MessageToByteEncoder<MessageProtocol> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol, ByteBuf byteBuf) throws Exception {
System.out.println("MyMessageEncoder encode 方法被调用");
byteBuf.writeInt(messageProtocol.getLen());
byteBuf.writeBytes(messageProtocol.getContent());
}
}
public class MyMessageDecoder extends ReplayingDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
System.out.println("message Decoder 被调用");
//需要将得到的二进制字节码->MessageProtocol 数据包(对象)
int len=byteBuf.readInt();
byte[] content=new byte[len];
byteBuf.readBytes(content);
//封装成MessageProtocol对象放入out,传递给下一个handler业务处理
MessageProtocol messageProtocol=new MessageProtocol();
messageProtocol.setLen(len);
messageProtocol.setContent(content);
list.add(messageProtocol);
}
}
客户端
public class MyClient {
public static void main(String[] args) {
EventLoopGroup group=new NioEventLoopGroup();
try{
Bootstrap boot=new Bootstrap();
boot.group(group)
.channel(NioSocketChannel.class)
.handler(new MyClientInitializer());//自定义初始化类
ChannelFuture channelFuture = boot.connect("localhost", 7000).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
group.shutdownGracefully();
}
}
}
public class MyClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline=socketChannel.pipeline();
pipeline.addLast(new MyMessageEncoder());//加入编码器
pipeline.addLast(new MyMessageDecoder());//解码器
pipeline.addLast(new MyClientHandler());
}
}
public class MyClientHandler extends SimpleChannelInboundHandler <MessageProtocol>{
private int count;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//发送十条数据“今天天气冷吃火锅”
for(int i=0;i<10;i++){
String s="今天天气冷,吃火锅";
byte[] content=s.getBytes(Charset.forName("utf-8"));
int length=s.getBytes(Charset.forName("utf-8")).length;
//创建协议包对象
MessageProtocol messageProtocol=new MessageProtocol();
messageProtocol.setLen(length);
messageProtocol.setContent(content);
ctx.writeAndFlush(messageProtocol);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("发生了异常"+cause.getMessage());
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
int len=msg.getLen();
byte[] content=msg.getContent();
System.out.println("客户端收到的消息如下:");
System.out.println("长度="+len);
System.out.println("内容="+new String(content,Charset.forName("utf-8")));
System.out.println("客户端接收消息数量="+(++this.count));
}
}