Added the uptime client example

This commit is contained in:
Trustin Lee 2009-09-10 05:42:13 +00:00
parent c36812d55d
commit 1b5a02a949
2 changed files with 177 additions and 0 deletions

View File

@ -0,0 +1,78 @@
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.jboss.netty.example.uptime;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
/**
* Connects to a server periodically to measure the uptime of the server.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
*
* @version $Rev: 1685 $, $Date: 2009-08-28 16:15:49 +0900 (Fri, 28 Aug 2009) $
*/
public class UptimeClient {
// Sleep 5 seconds before a reconnection attempt.
static final int RECONNECT_DELAY = 5;
// Reconnect when the server sends nothing for 10 seconds.
private static final int READ_TIMEOUT = 10;
public static void main(String[] args) throws Exception {
// Print usage if no argument is specified.
if (args.length != 2) {
System.err.println(
"Usage: " + UptimeClient.class.getSimpleName() +
" <host> <port>");
return;
}
// Parse options.
String host = args[0];
int port = Integer.parseInt(args[1]);
// Initialize the timer that schedules subsequent reconnection attempts.
Timer timer = new HashedWheelTimer();
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.getPipeline().addLast(
"timeout", new ReadTimeoutHandler(timer, READ_TIMEOUT));
bootstrap.getPipeline().addLast(
"handler", new UptimeClientHandler(bootstrap, timer));
bootstrap.setOption(
"remoteAddress", new InetSocketAddress(host, port));
// Initiate the first connection attempt - the rest is handled by
// UptimeClientHandler.
bootstrap.connect();
}
}

View File

@ -0,0 +1,99 @@
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.jboss.netty.example.uptime;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;
/**
* Keep reconnecting to the server while printing out the current uptime and
* connection attempt status.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
*
* @version $Rev: 1685 $, $Date: 2009-08-28 16:15:49 +0900 (Fri, 28 Aug 2009) $
*/
@ChannelPipelineCoverage("one")
public class UptimeClientHandler extends SimpleChannelUpstreamHandler {
final ClientBootstrap bootstrap;
private final Timer timer;
private volatile long startTime = -1;
public UptimeClientHandler(ClientBootstrap bootstrap, Timer timer) {
this.bootstrap = bootstrap;
this.timer = timer;
}
InetSocketAddress getRemoteAddress() {
return (InetSocketAddress) bootstrap.getOption("remoteAddress");
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
println("Disconnected from: " + getRemoteAddress());
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + "s");
timer.newTimeout(new TimerTask() {
public void run(Timeout timeout) throws Exception {
println("Reconnecting to: " + getRemoteAddress());
bootstrap.connect();
}
}, UptimeClient.RECONNECT_DELAY, TimeUnit.SECONDS);
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
println("Connected to: " + getRemoteAddress());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
Throwable cause = e.getCause();
if (cause instanceof ConnectException) {
startTime = -1;
println("Failed to connect: " + cause.getMessage());
}
ctx.getChannel().close();
}
void println(String msg) {
if (startTime < 0) {
System.err.format("[SERVER IS DOWN] %s%n", msg);
} else {
System.err.format("[UPTIME: %5ds] %s%n", (System.currentTimeMillis() - startTime) / 1000, msg);
}
}
}