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

org.smartboot.http.common.utils.FixedLengthFrameDecoder Maven / Gradle / Ivy

There is a newer version: 2.5.1
Show newest version
/*******************************************************************************
 * Copyright (c) 2017-2020, org.smartboot. All rights reserved.
 * project name: smart-http
 * file name: FixedLengthFrameDecoder.java
 * Date: 2020-01-01
 * Author: sandao ([email protected])
 ******************************************************************************/

package org.smartboot.http.common.utils;

import java.nio.ByteBuffer;

/**
 * 指定长度的解码器
 *
 * @author 三刀
 * @version V1.0 , 2017/10/20
 */
public class FixedLengthFrameDecoder implements SmartDecoder{
    private ByteBuffer buffer;
    private boolean finishRead;

    public FixedLengthFrameDecoder(int frameLength) {
        if (frameLength <= 0) {
            throw new IllegalArgumentException("frameLength must be a positive integer: " + frameLength);
        } else {
            buffer = ByteBuffer.allocate(frameLength);
        }
    }

    public boolean decode(ByteBuffer byteBuffer) {
        if (finishRead) {
            throw new RuntimeException("delimiter has finish read");
        }
        if (buffer.remaining() >= byteBuffer.remaining()) {
            buffer.put(byteBuffer);
        } else {
            int limit = byteBuffer.limit();
            byteBuffer.limit(byteBuffer.position() + buffer.remaining());
            buffer.put(byteBuffer);
            byteBuffer.limit(limit);
        }

        if (buffer.hasRemaining()) {
            return false;
        }
        buffer.flip();
        finishRead = true;
        return true;
    }

    public ByteBuffer getBuffer() {
        return buffer;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy