vince
2024-03-15 bf34444f482223d291830c13cb147392298d99ee
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
package com.fzzy.protocol.xsyg.client;
 
import com.fzzy.api.utils.BytesUtil;
import com.fzzy.api.utils.SpringUtil;
import com.fzzy.protocol.xsyg.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;
 
    @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());
        ClientEngine.defaultChannel = null;
 
    }
 
    @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);
 
        if (null == analysisService) {
            analysisService = SpringUtil.getBean(AnalysisService.class);
        }
 
       try{
           analysisService.analysis(socketAddress.getAddress(), socketAddress.getPort(), strMsg);
       }catch (Exception e){
           log.error(e.getMessage(),e);
       }
 
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
 
}