1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.uptime;
17
18 import java.net.ConnectException;
19 import java.net.InetSocketAddress;
20 import java.util.concurrent.TimeUnit;
21
22 import org.jboss.netty.bootstrap.ClientBootstrap;
23 import org.jboss.netty.channel.ChannelHandlerContext;
24 import org.jboss.netty.channel.ChannelStateEvent;
25 import org.jboss.netty.channel.ExceptionEvent;
26 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
27 import org.jboss.netty.handler.timeout.ReadTimeoutException;
28 import org.jboss.netty.util.Timeout;
29 import org.jboss.netty.util.Timer;
30 import org.jboss.netty.util.TimerTask;
31
32
33
34
35
36
37
38
39
40
41 public class UptimeClientHandler extends SimpleChannelUpstreamHandler {
42
43 final ClientBootstrap bootstrap;
44 private final Timer timer;
45 private long startTime = -1;
46
47 public UptimeClientHandler(ClientBootstrap bootstrap, Timer timer) {
48 this.bootstrap = bootstrap;
49 this.timer = timer;
50 }
51
52 InetSocketAddress getRemoteAddress() {
53 return (InetSocketAddress) bootstrap.getOption("remoteAddress");
54 }
55
56 @Override
57 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
58 println("Disconnected from: " + getRemoteAddress());
59 }
60
61 @Override
62 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
63 println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + "s");
64 timer.newTimeout(new TimerTask() {
65 public void run(Timeout timeout) throws Exception {
66 println("Reconnecting to: " + getRemoteAddress());
67 bootstrap.connect();
68 }
69 }, UptimeClient.RECONNECT_DELAY, TimeUnit.SECONDS);
70 }
71
72 @Override
73 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
74 if (startTime < 0) {
75 startTime = System.currentTimeMillis();
76 }
77
78 println("Connected to: " + getRemoteAddress());
79 }
80
81 @Override
82 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
83 Throwable cause = e.getCause();
84 if (cause instanceof ConnectException) {
85 startTime = -1;
86 println("Failed to connect: " + cause.getMessage());
87 }
88 if (cause instanceof ReadTimeoutException) {
89
90 println("Disconnecting due to no inbound traffic");
91 }
92 else {
93 cause.printStackTrace();
94 }
95 ctx.getChannel().close();
96 }
97
98 void println(String msg) {
99 if (startTime < 0) {
100 System.err.format("[SERVER IS DOWN] %s%n", msg);
101 } else {
102 System.err.format("[UPTIME: %5ds] %s%n", (System.currentTimeMillis() - startTime) / 1000, msg);
103 }
104 }
105 }