FixedLengthFrameDecoder是固定长度解码器,它根据指定的长度自动对消息进行解码,开发者不需要考虑TCP拆包/粘包问题。
下面通过一个例子进行说明。

服务端:
在服务端的ChannelPipleline中增加FixedLengthFrameDecoder,长度设置为20,然后依次增加字符串解码器和自定义的EchoServerHandler。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * 使用FixedLengthFrameDecoder解码器解决TCP粘包/拆包问题。
 *
 * @author j.tommy
 * @version 1.0
 * @date 2017/11/18
 */
public class EchoServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(20)); // 固定长度解码器,长度设置为20
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new EchoServerHandler());
                    }
                });
        try {
            ChannelFuture f = b.bind(8899).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
class EchoServerHandler extends ChannelHandlerAdapter {
    private int counter;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("接收到客户端请求:" + body + ",counter=" + ++counter);
        // 响应客户端
        ByteBuf resp = Unpooled.copiedBuffer(body.getBytes());
        ctx.write(resp);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}

客户端:
在客户端的ChannelPipleline中增加FixedLengthFrameDecoder,长度设置为20,然后依次增加字符串解码器和自定义的EchoClientHandler。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * @author j.tommy
 * @version 1.0
 * @date 2017/11/18
 */
public class EchoClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true).handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(20));
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(new EchoClientHandler());
            }
        });
        try {
            ChannelFuture f = b.connect("127.0.0.1",8899).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            group.shutdownGracefully();
        }
    }
}
class EchoClientHandler extends ChannelHandlerAdapter {
    private int counter = 0;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String req = "hello,this message is from client.";
        ByteBuf sendBuf = null;
        for (int i=0;i<100;i++) {
            sendBuf = Unpooled.copiedBuffer(req.getBytes());
            ctx.writeAndFlush(sendBuf);
        }
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String resp = (String) msg;
        System.out.println("接收到服务端响应:"  + resp + ",counter=" + ++counter);
    }
}

示例中,客户端发送的消息是hello,this message is from client.
因为按照固定长度截取,所以服务端接收到的是这样的:

参考《Netty权威指南》