com.easy.remoting.netty.handler.EasyDecoder.java Source code

Java tutorial

Introduction

Here is the source code for com.easy.remoting.netty.handler.EasyDecoder.java

Source

/**
 * Copyright (C) 2010-2013 Alibaba Group Holding Limited
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easy.remoting.netty.handler;

import com.easy.remoting.protocol.Cmd;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

/**
 * netty?
 *
 * @author by xu.qiang
 * @date 2016/12/8.
 */
public class EasyDecoder extends LengthFieldBasedFrameDecoder {
    private static final Logger log = LoggerFactory.getLogger(EasyDecoder.class);

    private static final int FRAME_MAX_LENGTH = 8388608;//   8*1024*2014

    public EasyDecoder() {
        super(FRAME_MAX_LENGTH, 0, 4, 0, 4);

        /**
         * ??
         * *****************************************************
         * totallength |header legnth | header data | body    |*
         * *****************************************************
         * ???
         * ??header?
         * ?header?
         * ?body?
         *
         * ?LengthFieldBasedFrameDecoder    0-4-0-4
         * ????   +  +   
         */
    }

    @Override
    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;
        try {
            frame = (ByteBuf) super.decode(ctx, in);
            if (null == frame) {
                return null;
            }

            ByteBuffer byteBuffer = frame.nioBuffer();

            return Cmd.decode(byteBuffer);
        } catch (Exception e) {
            log.error("decode exception:{}", e);

            ctx.channel().close().addListener(ChannelFutureListener.CLOSE);

        } finally {
            if (null != frame) {
                frame.release();
            }
        }

        return null;
    }
}