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

xin.alum.aim.coder.WebEncoder Maven / Gradle / Ivy

There is a newer version: 1.9.6
Show newest version
package xin.alum.aim.coder;

import io.netty.util.ReferenceCountUtil;
import xin.alum.aim.config.DataAgreement;
import xin.alum.aim.constant.ChannelAttr;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.util.JSONUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.List;

public class WebEncoder extends MessageToMessageEncoder {

    protected final InternalLogger logger =
            InternalLoggerFactory.getInstance(this.getClass());

    @Override
    protected void encode(ChannelHandlerContext ctx, Transportable in, List list) {
        DataAgreement agreement = ctx.channel().attr(ChannelAttr.AGREEMENT).get();
        if (agreement == null) {
            return;
        }

        switch (agreement) {
            case Json:
            case Text:
                list.add(new TextWebSocketFrame(JSONUtils.toJSONString(in)));
                break;
            case Binary:
            case ProtoBuf:
                byte[] binary = in.getBody();
                ByteBufAllocator binAlloc = ctx.channel().config().getAllocator();
                ByteBuf binOut = binAlloc.buffer(binary.length);
                binOut.writeBytes(binary);
                list.add(new BinaryWebSocketFrame(binOut));
                break;
            default:
                logger.error("{}未知编码协议:{}", ctx.channel(), agreement);
                break;
        }
        ReferenceCountUtil.release(in);
    }
}