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

xin.alum.aim.coder.SocksEncoder 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.AIMConstant;
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.ReplayingDecoder;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.InvalidParameterException;
import java.util.List;

public class SocksEncoder extends MessageToMessageEncoder {

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

    @Override
    protected void encode(ChannelHandlerContext ctx, Transportable in, List list) throws Exception {
        if (!ctx.channel().isWritable()) {
            return;
        }
        DataAgreement agreement = ctx.channel().attr(ChannelAttr.AGREEMENT).get();
        if (agreement == null) {
            return;
        }
        ByteBufAllocator binAlloc = ctx.channel().config().getAllocator();
        boolean isTlv = false;
        ByteBuf binOut;
        byte[] binary;
        switch (agreement) {
            case Json:
            case Text:
                binary = (JSONUtils.toJSONString(in) + AIMConstant.TEXT_FRAME_Delimiters).getBytes(StandardCharsets.UTF_8);
                binOut = binAlloc.buffer(binary.length);
                binOut.writeBytes(binary);
                break;
            case Tlv:
                isTlv = true;
            case Binary:
            case ProtoBuf:
                binary = in.getBody();
                if (isTlv) {
                    binOut = binAlloc.buffer(binary.length + 4 + 4);
                    binOut.writeInt(in.getType());
                } else {
                    binOut = binAlloc.buffer(binary.length + 4);
                }
                binOut.writeInt(binary.length);
                binOut.writeBytes(binary);
                break;
            default:
                throw new InvalidParameterException("未知编码协议");
        }
        list.add(binOut);
        ReferenceCountUtil.release(in);
    }
}