package com.ruoyi.netty.communication;
|
|
import com.ruoyi.common.utils.netty.ConvertCode;
|
import com.ruoyi.common.utils.netty.NettyTool;
|
import io.netty.buffer.ByteBuf;
|
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.handler.codec.ByteToMessageDecoder;
|
import lombok.extern.slf4j.Slf4j;
|
|
import java.util.List;
|
|
/**
|
* @author Joker 解码插件
|
*/
|
@Slf4j
|
public class SocketDecoder extends ByteToMessageDecoder {
|
|
/**
|
* 编码插件,接受到的数据在此处进行过滤,做拆包粘包处理等操作
|
*/
|
@Override
|
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
|
|
|
// log.info("----------------------------"+convertByteBufToString(in));
|
// convertByteBufToString(in);
|
byte[] orignalBytes = new byte[in.readableBytes()];
|
|
|
in.getBytes(in.readerIndex(), orignalBytes);
|
if (in.readableBytes() <= 0) {
|
return;
|
}
|
// TODO 做粘包处理
|
|
byte[] bytes = new byte[in.readableBytes()];
|
|
in.readBytes(bytes, 0, bytes.length);
|
out.add(bytes);
|
|
|
/*
|
得打的数据 需要解码 需要直接读取数据做
|
*/
|
// byte[] orignalBytes = new byte[in.readableBytes()];
|
//
|
//
|
// in.getBytes(in.readerIndex(), orignalBytes);
|
// if (in.readableBytes() <= 0) {
|
// return;
|
// }
|
// // TODO 做粘包处理
|
//
|
// byte[] bytes = new byte[in.readableBytes()];
|
//设置数据 指定读取地址
|
// in.readBytes(bytes, 0, in.readableBytes());
|
/*
|
数据过滤 比较暴力的是 只有符合 CRC16校验即可通过 如果数据不等则而直接 不读取数据
|
// */
|
// if (NettyTool.determineCRC16High(ConvertCode.bytes2Str(orignalBytes))){
|
// in.readBytes(bytes, 0, in.readableBytes());
|
// out.add(bytes);
|
// }else {
|
// //设置 指针偏移 可以 解决数据 粘包
|
// in.readerIndex(orignalBytes.length);
|
//
|
//// 看情况如果需要则需要则可以添加额外的数据结果
|
//// byte[] LeegBaty = new byte[0];
|
//// out.add(LeegBaty);
|
//// return;
|
// }
|
|
}
|
|
|
|
@Override
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
log.info("unexpected exception", cause);
|
}
|
}
|