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.bootstrap.Bootstrap;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.ChannelFutureListener;
21 import io.netty.channel.ChannelInitializer;
22 import io.netty.channel.EventLoopGroup;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.channel.socket.SocketChannel;
25 import io.netty.channel.socket.nio.NioSocketChannel;
26 import io.netty.handler.timeout.IdleStateHandler;
27
28
29
30
31
32
33
34 public final class UptimeClient {
35
36 static final String HOST = System.getProperty("host", "127.0.0.1");
37 static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));
38
39 static final int RECONNECT_DELAY = Integer.parseInt(System.getProperty("reconnectDelay", "5"));
40
41 private static final int READ_TIMEOUT = Integer.parseInt(System.getProperty("readTimeout", "10"));
42
43 private static final UptimeClientHandler handler = new UptimeClientHandler();
44 private static final Bootstrap bs = new Bootstrap();
45
46 public static void main(String[] args) throws Exception {
47 EventLoopGroup group = new NioEventLoopGroup();
48 bs.group(group)
49 .channel(NioSocketChannel.class)
50 .remoteAddress(HOST, PORT)
51 .handler(new ChannelInitializer<SocketChannel>() {
52 @Override
53 protected void initChannel(SocketChannel ch) throws Exception {
54 ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);
55 }
56 });
57 bs.connect();
58 }
59
60 static void connect() {
61 bs.connect().addListener(new ChannelFutureListener() {
62 @Override
63 public void operationComplete(ChannelFuture future) throws Exception {
64 if (future.cause() != null) {
65 handler.startTime = -1;
66 handler.println("Failed to connect: " + future.cause());
67 }
68 }
69 });
70 }
71 }