liurunyu
2024-08-15 f7e731bdc2fce4445c0d22993134c6c2b07d207b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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);
    }
}