import java.time.LocalDateTime;
import java.util.*;
import org.apache.commons.lang.time.DateUtils;
import com.liangxs.commom.HexUtils;
import com.liangxs.commom.SpringUtils;
import io.netty.buffer.Unpooled;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import com.liangxs.logger.Logger;
import com.liangxs.logger.LoggerFactory;
import io.netty.util.ReferenceCountUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class DianciCustomDecoder extends MessageToMessageDecoder<ByteBuf>{
private byte[] remainingBytes;
private ByteBuf currBB = null;
Logger log = LoggerFactory.getLogger(LoggerFactory.MY_INFO_LOG);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.WRITER_IDLE) {
} else if (e.state() == IdleState.READER_IDLE) {
ctx.channel().close();
}
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String channelId = ctx.channel().id().asLongText();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
state = false;
SpringUtils.getBean(com.liangxs.dbapi.javaDyAdmin.DianchiDataParseService.class).setChannel(null);
String channelId = ctx.channel().id().asLongText();
ctx.close();
super.channelInactive(ctx);
}
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
if(remainingBytes == null) {
currBB = msg;
}else {
byte[] tb = new byte[remainingBytes.length + msg.readableBytes()];
System.arraycopy(remainingBytes, 0, tb, 0, remainingBytes.length);
byte[] vb = new byte[msg.readableBytes()];
msg.readBytes(vb);
System.arraycopy(vb, 0, tb, remainingBytes.length, vb.length);
currBB = Unpooled.copiedBuffer(tb);
}
while(currBB.readableBytes() > 0) {
if(!dodecode(ctx, currBB, out)) {
break;
}
}
if(currBB.readableBytes() > 0) {
remainingBytes = new byte[currBB.readableBytes()];
currBB.readBytes(remainingBytes);
}else {
remainingBytes = null;
}
}
protected boolean dodecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() > 3) {
in.markReaderIndex();
byte head = in.readByte();
int length = in.readShort();
if ( in.readableBytes() < length - 3) {
in.resetReaderIndex();
return false;
}
if(in.readableBytes() > 0)
return true;
return false;
}
return false;
}
}