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

com.zhuang.netty.handler.decoder.SimpleDemoDecoder Maven / Gradle / Ivy

package com.zhuang.netty.handler.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class SimpleDemoDecoder extends ByteToMessageDecoder {
    // 协议头长度为 4 个字节
    private static final int HEADER_LENGTH = 4;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) {
        // 未接收完消息头
        if (in.readableBytes() < HEADER_LENGTH) {
            return;
        }
        // 标记读取位置
        in.markReaderIndex();
        // 读取协议头,即消息体长度
        int bodyLength = in.readInt();
        if (bodyLength < 0) {
            log.info("Wrong header data -> length=" + bodyLength);
            // 标识已读,丢弃数据
            in.readerIndex(in.writerIndex());
            return;
        }
        // 未接收完消息体
        if (in.readableBytes() < bodyLength) {
            // 重置读取位置
            in.resetReaderIndex();
            return;
        }

        // 读取消息体数据
        //ByteBuf data = in.readBytes(bodyLength);

        // 读取整个数据包
        in.resetReaderIndex();
        ByteBuf data = in.readBytes(HEADER_LENGTH + bodyLength);
        // 添加到输出列表
        out.add(data);
    }
}