在上篇博客中介绍了netty的helloworld,本篇来介绍netty的拆包粘包问题。
TCP是一个 流 的协议,所谓流就是没有界限的遗传数据,大家可以想象一下,如果河里的水相当于数据,他们是连成一片的,没有分界线,TCP底层并不了解上层的业务数据具体含义,他会根据TCP缓冲区的实际情况进行包的划分,也就是说在业务上,我们一个完整的包可能会被TCP分成多个包进行发送,也可能把多个小包封装成一个大的数据包发送出去,这就是所谓的拆包粘包问题。
并发编程网是这么说的:
先写一个小测试,在不进行处理的时候,代码如下:
package com.netty.test;
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) throws Exception {
//server端不需要接收连接所有只用一个work来处理连接就可以。
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());
}
});
//连接
ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
这里连续给服务端发送了三个hello world。
服务端接收的数据如下,没有分出个数:
接收服务器端返回信息:进行返回给客户端的响应hello worldhello worldhello world
接收返回信息完成
解决拆包粘包问题有三种主流的解决方案:
1.消息定长,例如每个报文的大小固定为200个字节,如果不够用空格补位。
2.在包的尾部增加特殊字符进行分割
3.将消息分为消息头和消息体,在消息头中包含表示消息总长度的字段,然后进行业务逻辑的处理
个人认为第二种方法最好,这里将第二种方法的代码贴出
server
package com.netty.unpack1;
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.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;
public class Server {
public static void main(String[] args) throws InterruptedException {
//用来接收客户端传进来的连接
NioEventLoopGroup boss = new NioEventLoopGroup();
//用来处理已被接收的连接
NioEventLoopGroup work = new NioEventLoopGroup();
//辅助类 用于帮助我们创建netty服务
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, work)
.channel(NioServerSocketChannel.class)//设置NIO模式
.option(ChannelOption.SO_BACKLOG, 1024)//设置tcp缓冲区
.childOption(ChannelOption.SO_SNDBUF, 32*1024)//设置发送缓冲区数据大小
.option(ChannelOption.SO_RCVBUF, 32*1024)//设置接收缓冲区数据大小
.childOption(ChannelOption.SO_KEEPALIVE, true)//保持长连接
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//设置特殊分隔符
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));//1024指的是分隔符长度可以为多少长度,此处分隔符长度为2个长度
//设置字符串形式的解码(这里就不用buf了)
ch.pipeline().addLast(new StringDecoder());
//通道的初始化,数据传输过来进行拦截及执行
ch.pipeline().addLast(new ServerHandler());
}
});
ChannelFuture f = serverBootstrap.bind(8888).sync();//绑定端口启动服务
f.channel().closeFuture().sync();
work.shutdownGracefully();
boss.shutdownGracefully();
}
}
serverHandler
package com.netty.unpack1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ServerHandler extends ChannelInboundHandlerAdapter{
/**
* 通道激活
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("数据激活");
}
/**
* 通道数据读取
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String msgStr = (String) msg;
System.out.println("服务器收到数据:"+msgStr);
String response="进行返回给客户端的响应"+msgStr+"$_";
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("数据读取完毕");
}
}
client
package com.netty.unpack1;
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.string.StringDecoder;
public class Client {
public static void main(String[] args) throws Exception {
//server端不需要接收连接所有只用一个work来处理连接就可以。
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//设置特殊分隔符
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));//1024指的是分隔符长度可以为多少长度,此处分隔符长度为2个长度
//设置字符串形式的解码(这里就不用buf了)
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ClientHandler());
}
});
//连接
ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello world$_".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello world$_".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello world$_".getBytes()));
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
clientHandler
package com.netty.unpack1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
/**
* 通道数据读取
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String strMsg = (String) msg;
System.out.println("接收服务器端返回信息:"+strMsg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("接收返回信息完成");
}
}
打印信息如下:
server端
数据激活
服务器收到数据:hello world
服务器收到数据:hello world
服务器收到数据:hello world
数据读取完毕
client端
接收服务器端返回信息:进行返回给客户端的响应hello world
接收服务器端返回信息:进行返回给客户端的响应hello world
接收服务器端返回信息:进行返回给客户端的响应hello world
接收返回信息完成
拆包粘包到这里就OK了 。