最近需要用netty写一个fota升级服务器,本来一些基本功能都是实现了,每一个API都测试通过了。但是后来多条API同时测试的时候出了问题。
比如,客户端发一个[0,1,2](意思是,请求有3个字节,分别是1、2、3)的请求,服务器不响应;客户端发[3,4,5]的请求,服务器响应“OK”。
目前一切都正常,但是如果客户端的这两个请求是连续发送的,第一个请求由于没有响应,导致第二个请求可能在第一个请求发出去之后的1ms之内也发送出去,这个时候我发现客户端收不到“OK”的响应了,而服务器收到了[0,1,2,3,4,5]的数据,这就是发生了数据的粘包情况。
当然,同一条API发送过快,且在一条连接中进行的话, 同样会出现这种情况,下面用代码模拟。
1,相关lib包
2,服务端
NettyServer
package com.zhuyun.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;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import java.net.InetSocketAddress;
import com.zhuyun.server.handler.ServerHandler;
import com.zhuyun.server.handler.TcpDecoder;
/**
* Netty 服务端代码
*
* @author zhouyinfei
*/
public class NettyServer {
private final int port;
public NettyServer(int port){
this.port = port;
}
public void start() throws Exception{
EventLoopGroup bossGroup = new NioEventLoopGroup(); //创建EventLoopGroup
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap(); //创建ServerBootstrap
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) //指定使用一个NIO传输Channel
.localAddress(new InetSocketAddress(port)) //用指定的端口设置socket地址
.childHandler(new ChannelInitializer<SocketChannel>() { //在Channel的ChannelPipeline中加入EchoServerHandler
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ByteArrayDecoder());//字节数组解码
// ch.pipeline().addLast(new TcpDecoder());
ch.pipeline().addLast(new ByteArrayEncoder());//字节数组编码
ch.pipeline().addLast(new ServerHandler());//EchoServerHandler是@Sharable的,所以我们可以一直用同一个实例
}
})
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_REUSEADDR,true)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind().sync();//异步的绑定服务器,sync()一直等到绑定完成
System.out.println("服务器启动成功...");
f.channel().closeFuture().sync();//获得这个Channel的CloseFuture,阻塞当前线程直到关闭操作完成
}finally{
workerGroup.shutdownGracefully().sync();//关闭EventLoopGroup,释放所有资源
bossGroup.shutdownGracefully().sync();//关闭EventLoopGroup,释放所有资源
}
}
public static void main(String args[]) throws Exception {
new NettyServer(9999).start();
}
}
ServerHandler
package com.zhuyun.server.handler;
import java.util.Arrays;
import com.zhuyun.util.DataParseUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
@Sharable //表明一个ChannelHandler可以被多个Channel安全的共享
public class ServerHandler extends SimpleChannelInboundHandler<byte[]> {
private int counter;
@Override
public void channelRead0(ChannelHandlerContext ctx, byte[] data) throws Exception {// 每次收到消息时被调用
System.out.println("Server receive: " + Arrays.toString(data) + "; counter=" + ++counter);
ctx.writeAndFlush(data);
}
@Override //用来通知handler上一个ChannelRead()是被这批消息中的最后一个消息调用
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//刷新挂起的数据到远端,然后关闭Channel
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
@Override //在读操作异常被抛出时被调用
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace(); //打印异常堆栈跟踪消息
ctx.close(); //关闭这个Channel
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
}
}
服务端每次接收到请求,都打印接收的数据,同时计数器加1。
3,客户端
NettyClient
package com.zhuyun.client;
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.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import java.net.InetSocketAddress;
import com.zhuyun.client.handler.ClientHandler;
/**
* Netty 客户端代码
*
* @author zhouyinfei
*/
public class NettyClient implements Runnable{
private final String host;
private final int port;
public NettyClient(String host, int port){
this.host = host;
this.port = port;
}
public void start() throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap(); //创建Bootstrap
b.group(group) //指定EventLoopGroup来处理客户端事件;需要EventLoopGroup的NIO实现
.channel(NioSocketChannel.class) //用于NIO传输的Channel类型
.remoteAddress(new InetSocketAddress(host, port)) //设置服务器的InetSocketAddress
.handler(new ChannelInitializer<SocketChannel>() { //当一个Channel创建时,把一个EchoClientHandler加入它的pipeline中
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ByteArrayDecoder());//字节数组解码
ch.pipeline().addLast(new ByteArrayEncoder());//字节数组编码
ch.pipeline().addLast(new ClientHandler());
}
})
.option(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.connect().sync(); //连接到远端,一直等到连接完成
f.channel().closeFuture().sync(); //一直阻塞到Channel关闭
}finally{
group.shutdownGracefully().sync(); //关闭所有连接池,释放所有资源
}
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
this.start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
// ExecutorService es = Executors.newFixedThreadPool(1);
// for (int i = 0; i < 1; i++) {
// es.execute(new NettyClient("192.168.10.200", 9999));
// }
new NettyClient("localhost", 9999).start();
}
}
ClientHandler
package com.zhuyun.client.handler;
import java.util.Arrays;
import com.zhuyun.util.DataParseUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@Sharable //标记这个类的实例可以被多个Channel共享
public class ClientHandler extends SimpleChannelInboundHandler<byte[]>{
private int counter;
@Override //和服务器的连接建立起来后被调用
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// //当收到连接成功的通知,发送一条消息
System.out.println("已经与Server建立连接。。。。");
byte[] b = {1,2,3};
for (int i = 0; i < 300; i++) {
ctx.writeAndFlush(b);
}
}
@Override //从服务器收到一条消息时被调用
protected void channelRead0(ChannelHandlerContext ctx, byte[] data) throws Exception {
System.out.println("Client received: " + Arrays.toString(data) + ", counter=" + ++counter);//打印收到的消息到日志
// ctx.close();
}
@Override //处理过程中异常发生时被调用
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();//异常发生时,记录错误日志,关闭Channel
ctx.close();
}
}
客户端在同一个连接里循环300次,发送字节数组[1,2,3]
4,运行结果
预期中,每次接收的数据是[1,2,3],counter=100,但是粘包后就会发生上述的情况。
5,解决方案
主要有三种:
LineBasedFrameDecoder:每个完整请求的结尾加上行分隔符\r 或者\r\n,Java中使用System.getProperty("line.separator")即可。
DeLimiterBasedFrameDecoder: 加特殊分隔符,例如 "$_"
FixedLengthFrameDecoder: 固定长度