[测评系统]--测评系统核心代码库
linzhijie
2021-03-11 84fea994d2db7dc313ad1774f34eb12a45f8d6e7
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
package com.ots.project.tool.report.reportCalculation.socket.netty;
import com.alibaba.fastjson.JSON;
import com.ots.project.tool.report.reportCalculation.response.ReportAPIResult;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import java.util.concurrent.TimeUnit;
 
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
    private NettyClient nettyClient;
    private int attempts = 0;
    public NettyClientHandler(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String response) {
        ReportAPIResult reportAPIResult = JSON.parseObject(response, ReportAPIResult.class);
        System.out.println("service response message:" + JSON.toJSON(reportAPIResult));
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("output connected!");
        attempts = 0;
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("offline");
        
        final EventLoop eventLoop = ctx.channel().eventLoop();
        if (attempts < 12) {
            attempts++;
        }
        int timeout = 2 << attempts;
        eventLoop.schedule(() -> {
            try {
                nettyClient.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, timeout, TimeUnit.SECONDS);
        ctx.fireChannelInactive();
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                System.out.println("READER_IDLE");
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                
                String s = "NettyClient..." + System.getProperty("line.separator");
                ctx.channel().writeAndFlush(s);  
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                System.out.println("ALL_IDLE");
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}