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

shz.net.netty.NettyDecoderHandler Maven / Gradle / Ivy

There is a newer version: 10.1.1
Show newest version
package shz.net.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import shz.core.AccessibleCacheHelp;
import shz.core.Serializer;

import java.util.List;

public class NettyDecoderHandler extends ByteToMessageDecoder {
    private final Class cls;

    public NettyDecoderHandler() {
        cls = AccessibleCacheHelp.getParameterizedType(getClass(), NettyDecoderHandler.class, "I");
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) {
        if (in.readableBytes() < length()) return;
        in.markReaderIndex();
        int len;
        if ((len = in.readInt()) < 0) ctx.close();
        if (in.readableBytes() < len) {
            in.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[len];
        in.readBytes(bytes);
        I msg = deserialize(bytes, cls);
        out.add(msg);
    }

    protected int length() {
        return 4;
    }

    protected  T deserialize(byte[] bytes, Class cls) {
        return Serializer.deserialize(bytes);
    }
}