ITPub博客

首页 > IT职业 > IT生活 > netty自定义Decoder用于自定义协议

netty自定义Decoder用于自定义协议

IT生活 作者:neuyu 时间:2021-09-09 09:00:51 0 删除 编辑

在使用netty时由于自定义协议的分割符是在数据包体的头部,netty提供的DelimiterBasedFrameDecoder并不能满足我们的需求。


自定义的decode如下

package com.llvision.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author yd
 * 2017/04/08
 */
public class CustomFrameDecoder  extends ByteToMessageDecoder {
    private final Logger logger= LoggerFactory.getLogger(CustomFrameDecoder.class);
    private static int HEADER_SIZE = 4;
    private final ByteBuf delimiter;
    private final int maxFrameLength;
    private static ByteBuf buf = Unpooled.buffer();

    public CustomFrameDecoder(int maxFrameLength,ByteBuf delimiter ) {
        this.delimiter = delimiter;
        this.maxFrameLength = maxFrameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        Object decoded = this.decode(ctx, in);
        if(decoded != null) {
            out.add(decoded);
        }
    }

    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        in.markReaderIndex();
        int headerOffset = indexOf(in, delimiter);
        if (headerOffset 

但在使用该解码器用客户端施加压力时,可达到1s 2000个的数据并发量。当大于这个量时会方式解析崩溃的问题,猜测是Tcp粘包的问题。也可能是机器性能问题。还请解答

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4550/viewspace-2807682/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-20

  • 博文量
    94
  • 访问量
    14048