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

cn.godmao.netty.codec.DefaultEncoder Maven / Gradle / Ivy

There is a newer version: 2.3.4.7.Beat
Show newest version
package cn.godmao.netty.codec;

import cn.godmao.utils.KryoUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.EncoderException;

public class DefaultEncoder implements IEncoder {

    @Override
    public ByteBuf encode(Object message) throws EncoderException {
        if (null == message) {
            return null;
        }
        final ByteBuf byteBuf;
        if (message instanceof ByteBuf) {
            byteBuf = ((ByteBuf) message).retainedDuplicate();
        } else if (message instanceof byte[]) {
            byteBuf = Unpooled.wrappedBuffer((byte[]) message);
        } else {
            final byte[] message_bytes = KryoUtil.serialize(message);
            if (null == message_bytes) {
                return null;
            }
            byteBuf = ByteBufAllocator.DEFAULT.buffer(message_bytes.length);
            byteBuf.writeBytes(message_bytes);
        }
        return byteBuf;
    }

    public static DefaultEncoder me() {
        return DefaultEncoder.Holder.ME;
    }


    private static class Holder {
        static final DefaultEncoder ME = new DefaultEncoder();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy