Netty使用DelimiterBasedFrameDecoder解决TCP粘包拆包问题

灰太狼 2022-05-13 10:04 587阅读 0赞

通过对DelimiterBasedFrameDecoder的使用,我们可以自动完成分隔符为结束标识的消息的解码。

下面的例子中,将$_作为分隔符。

服务端代码:

  1. /** * 使用DelimiterBasedFrameDecoder解码器解决TCP粘包/拆包问题。 * * @author j.tommy * @version 1.0 * @date 2017/11/17 */
  2. public class EchoServer {
  3. protected final static String DELIMITER = "$_";
  4. public static void main(String[] args) {
  5. EventLoopGroup bossGroup = new NioEventLoopGroup();
  6. EventLoopGroup workerGroup = new NioEventLoopGroup();
  7. ServerBootstrap b = new ServerBootstrap();
  8. b.group(bossGroup, workerGroup)
  9. .channel(NioServerSocketChannel.class)
  10. .option(ChannelOption.SO_BACKLOG, 1024)
  11. .handler(new LoggingHandler(LogLevel.INFO))
  12. .childHandler(new ChannelInitializer<SocketChannel>() {
  13. protected void initChannel(SocketChannel socketChannel) throws Exception {
  14. ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER.getBytes());
  15. socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter)); // 这里的1024标识单条消息的最大长度,如果达到长度后仍然没有读取到分隔符,就抛出TooLongFrameException,防止由于异常码流缺失导致的内存溢出,这是Netty解码器的可靠性保护;第二个参数是分隔符
  16. socketChannel.pipeline().addLast(new StringDecoder());
  17. socketChannel.pipeline().addLast(new EchoServerHandler());
  18. }
  19. });
  20. try {
  21. ChannelFuture f = b.bind(8899).sync();
  22. f.channel().closeFuture().sync();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. } finally {
  26. bossGroup.shutdownGracefully();
  27. workerGroup.shutdownGracefully();
  28. }
  29. }
  30. }
  31. class EchoServerHandler extends ChannelHandlerAdapter {
  32. private int counter;
  33. @Override
  34. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  35. ctx.close();
  36. }
  37. @Override
  38. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  39. String body = (String) msg;
  40. System.out.println("接收到客户端请求:" + body + ",counter=" + ++counter);
  41. // 响应客户端
  42. body += EchoServer.DELIMITER;
  43. ByteBuf resp = Unpooled.copiedBuffer(body.getBytes());
  44. ctx.write(resp);
  45. }
  46. @Override
  47. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  48. ctx.flush();
  49. }
  50. }

客户端代码:

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

参考《Netty权威指南》

发表评论

表情:
评论列表 (有 0 条评论,587人围观)

还没有评论,来说两句吧...

相关阅读

    相关 NettyTCP问题

           粘包拆包问题是处于网络比较底层的问题,在数据链路层、网络层以及传输层都有可能发生。我们日常的网络应用开发大都在传输层进行,由于UDP有消息保护边界,不会发生这个问