1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.example.uptime;
17
18 import io.netty5.channel.ChannelHandlerContext;
19 import io.netty5.channel.SimpleChannelInboundHandler;
20 import io.netty5.handler.timeout.IdleState;
21 import io.netty5.handler.timeout.IdleStateEvent;
22
23 import java.util.concurrent.TimeUnit;
24
25
26
27
28
29 public class UptimeClientHandler extends SimpleChannelInboundHandler<Object> {
30
31 long startTime = -1;
32
33 @Override
34 public void channelActive(ChannelHandlerContext ctx) {
35 if (startTime < 0) {
36 startTime = System.currentTimeMillis();
37 }
38 println("Connected to: " + ctx.channel().remoteAddress());
39 }
40
41 @Override
42 public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
43
44 }
45
46 @Override
47 public void channelInboundEvent(ChannelHandlerContext ctx, Object evt) {
48 if (!(evt instanceof IdleStateEvent)) {
49 return;
50 }
51
52 IdleStateEvent e = (IdleStateEvent) evt;
53 if (e.state() == IdleState.READER_IDLE) {
54
55 println("Disconnecting due to no inbound traffic");
56 ctx.close();
57 }
58 }
59
60 @Override
61 public void channelInactive(final ChannelHandlerContext ctx) {
62 println("Disconnected from: " + ctx.channel().remoteAddress());
63 }
64
65 @Override
66 public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {
67 println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + 's');
68
69 ctx.channel().executor().schedule(() -> {
70 println("Reconnecting to: " + UptimeClient.HOST + ':' + UptimeClient.PORT);
71 UptimeClient.connect();
72 }, UptimeClient.RECONNECT_DELAY, TimeUnit.SECONDS);
73 }
74
75 @Override
76 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
77 cause.printStackTrace();
78 ctx.close();
79 }
80
81 void println(String msg) {
82 if (startTime < 0) {
83 System.err.format("[SERVER IS DOWN] %s%n", msg);
84 } else {
85 System.err.format("[UPTIME: %5ds] %s%n", (System.currentTimeMillis() - startTime) / 1000, msg);
86 }
87 }
88 }