View Javadoc

1   /*
2    * Copyright 2009 Red Hat, Inc.
3    *
4    * Red Hat licenses this file to you under the Apache License, version 2.0
5    * (the "License"); you may not use this file except in compliance with the
6    * License.  You may obtain a copy of the License at:
7    *
8    *    http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Keep reconnecting to the server while printing out the current uptime and
34   * connection attempt status.
35   *
36   * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
37   * @author <a href="http://gleamynode.net/">Trustin Lee</a>
38   *
39   * @version $Rev: 2189 $, $Date: 2010-02-19 18:02:57 +0900 (Fri, 19 Feb 2010) $
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              // The connection was OK but there was no traffic for last period.
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 }