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.util.Timeout;
28 import org.jboss.netty.util.Timer;
29 import org.jboss.netty.util.TimerTask;
30
31
32
33
34
35
36
37
38
39
40 public class UptimeClientHandler extends SimpleChannelUpstreamHandler {
41
42 final ClientBootstrap bootstrap;
43 private final Timer timer;
44 private long startTime = -1;
45
46 public UptimeClientHandler(ClientBootstrap bootstrap, Timer timer) {
47 this.bootstrap = bootstrap;
48 this.timer = timer;
49 }
50
51 InetSocketAddress getRemoteAddress() {
52 return (InetSocketAddress) bootstrap.getOption("remoteAddress");
53 }
54
55 @Override
56 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
57 println("Disconnected from: " + getRemoteAddress());
58 }
59
60 @Override
61 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
62 println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + "s");
63 timer.newTimeout(new TimerTask() {
64 public void run(Timeout timeout) throws Exception {
65 println("Reconnecting to: " + getRemoteAddress());
66 bootstrap.connect();
67 }
68 }, UptimeClient.RECONNECT_DELAY, TimeUnit.SECONDS);
69 }
70
71 @Override
72 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
73 if (startTime < 0) {
74 startTime = System.currentTimeMillis();
75 }
76
77 println("Connected to: " + getRemoteAddress());
78 }
79
80 @Override
81 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
82 Throwable cause = e.getCause();
83 if (cause instanceof ConnectException) {
84 startTime = -1;
85 println("Failed to connect: " + cause.getMessage());
86 }
87 ctx.getChannel().close();
88 }
89
90 void println(String msg) {
91 if (startTime < 0) {
92 System.err.format("[SERVER IS DOWN] %s%n", msg);
93 } else {
94 System.err.format("[UPTIME: %5ds] %s%n", (System.currentTimeMillis() - startTime) / 1000, msg);
95 }
96 }
97 }