All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xin.alum.aim.coder.ProtoDecoder Maven / Gradle / Ivy

There is a newer version: 1.9.6
Show newest version
package xin.alum.aim.coder;

import io.netty.util.ReferenceCountUtil;
import xin.alum.aim.config.DataAgreement;
import xin.alum.aim.constant.ChannelAttr;
import xin.alum.aim.model.Sent;
import xin.alum.aim.model.proto.SentProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

import java.util.ArrayList;
import java.util.List;

/**
 * Protobuf 协议转换
 *
 * @auther Alum(alum @ live.cn)
 * @date 2021/8/5 17:05
 */
public class ProtoDecoder extends ProtobufDecoder {

    public ProtoDecoder() {
        super(SentProto.Model.getDefaultInstance());
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List list) {
        ChannelPipeline pipeline = ctx.channel().pipeline();
        try {
            super.decode(ctx, in, list);
            if (list.size() > 0) {
                List out = new ArrayList<>();
                list.forEach(p -> {
                    SentProto.Model m = (SentProto.Model) p;
                    Sent sent = new Sent();
                    sent.setKey(m.getKey());
                    sent.setTimestamp(m.getTimestamp());
                    sent.putAll(m.getDataMap());
                    out.add(sent);
                });
                list.clear();
                list.addAll(out);
                ReferenceCountUtil.release(in);
            }
        } catch (Exception ex) {
            pipeline.remove(this);
            ctx.fireChannelRead(in.retain());
        }

    }
}