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 { 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); } }