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