package com.sv.netty.netty;

import com.sv.netty.utils.EncodeUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * TCP消息解码器
 *
 * @Author peakren
 * @Date 08/05/2017 10:34 PM
 */
public class MessageDecoder extends ByteToMessageDecoder {

    private final static int MESSAGE_LENGTH = 4;
    private final static int MESSAGE_SEQNO = 4;
    private final static int MESSAGE_HEAD = 8;
    private final static int MESSAGE_MAX_LENGTH = 12;
    private final static int MAGIC_WORD = 0x9DDD;  //码头

    private static Logger logger = LoggerFactory.getLogger(MessageDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.capacity() >= MESSAGE_MAX_LENGTH) {
            int magicWord = in.readInt();
            if (magicWord == MAGIC_WORD) {
                int length = in.readInt();
                byte[] msg = new byte[length];
                in.readBytes(msg);
                String message = new String(msg, "utf-8");
                out.add(message);
            }
        }
    }

}
