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

com.gateway.connector.tcp.codec.TcpProtoEncoder Maven / Gradle / Ivy

package com.gateway.connector.tcp.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gateway.connector.proto.Proto;
import com.gateway.connector.utils.ProtoUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class TcpProtoEncoder extends MessageToByteEncoder {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private boolean isGzip=false;
	public TcpProtoEncoder(boolean isGzip) {
		this.isGzip=isGzip;
	}
	@Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Proto proto, ByteBuf byteBuf) throws Exception {
    	logger.debug("encode: {}", proto);
    	proto.setBody(ProtoUtils.gzipBody(isGzip,proto.getBody()));
        int packageLenth = Proto.HEADER_LENGTH;
        byte[] sidByte = proto.getSessionId().getBytes();

        if (proto.getBody() != null)
            packageLenth = proto.getBody().length + packageLenth + sidByte.length;
        else
            packageLenth = packageLenth + sidByte.length;
        
        if (proto.getBody() != null) {
            byteBuf.writeInt(packageLenth);
            byteBuf.writeShort(Proto.HEADER_LENGTH);
            byteBuf.writeInt(proto.getCmd());
            byteBuf.writeShort(proto.getFormat());
            byteBuf.writeInt(proto.getSeq());
            byteBuf.writeInt(sidByte.length);
            if (sidByte.length != 0) {
                byteBuf.writeBytes(sidByte);
            }
         
            byteBuf.writeBytes(proto.getBody());
        } else {
            byteBuf.writeInt(Proto.HEADER_LENGTH + sidByte.length);
            byteBuf.writeShort(Proto.HEADER_LENGTH);
            byteBuf.writeInt(proto.getCmd());
            byteBuf.writeShort(proto.getFormat());
            byteBuf.writeInt(proto.getSeq());
            byteBuf.writeInt(sidByte.length);
            if (sidByte.length != 0) {
                byteBuf.writeBytes(sidByte);
            }
        }
          
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy