vince
2024-01-16 5f92b2034f84caeab9cb6efc61ecbe22407935b4
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
package com.fzzy.protocol.wujia.client;
 
import com.fzzy.api.utils.BytesUtil;
import com.fzzy.api.utils.SpringUtil;
import com.fzzy.protocol.wujia.analysis.AnalysisService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
 
import java.net.InetSocketAddress;
 
 
@Slf4j
public class ClientHandler extends SimpleChannelInboundHandler<Object> {
 
    private AnalysisService analysisService;
 
    private static String msgStr = "";
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel()
                .remoteAddress();
 
        log.info("连接终成功,IP={},port={}", socketAddress.getAddress()
                .getHostAddress(), socketAddress.getPort());
    }
 
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
 
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
 
        log.info("连接终端掉线,IP={},port={}", socketAddress.getAddress(), socketAddress.getPort());
 
 
    }
 
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        byte[] bytes = (byte[]) msg;
 
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
 
        String strMsg = BytesUtil.bytesToString(bytes);
 
        log.info("终端返回信息,IP={},port={},msg={}", socketAddress.getAddress(), socketAddress.getPort(), strMsg);
        msgStr+= strMsg;
 
        if(msgStr.endsWith("AABBCC")){
            log.info("消息接收完整开始解析,IP={},port={},msg={}", socketAddress.getAddress(), socketAddress.getPort(), msgStr);
 
            if (null == analysisService) {
                analysisService = SpringUtil.getBean(AnalysisService.class);
            }
            try{
                analysisService.analysis(socketAddress.getAddress(), socketAddress.getPort(), msgStr);
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
 
        }else{
            log.info("消息不完整,等待消息完整,IP={},port={},msg={}", socketAddress.getAddress(), socketAddress.getPort(), strMsg);
 
        }
 
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
 
}