1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.localtime;
17
18 import java.net.InetSocketAddress;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.concurrent.Executors;
24
25 import org.jboss.netty.bootstrap.ClientBootstrap;
26 import org.jboss.netty.channel.Channel;
27 import org.jboss.netty.channel.ChannelFuture;
28 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
29
30
31
32
33
34 public class LocalTimeClient {
35
36 private final String host;
37 private final int port;
38 private final Collection<String> cities;
39
40 public LocalTimeClient(String host, int port, Collection<String> cities) {
41 this.host = host;
42 this.port = port;
43 this.cities = new ArrayList<String>();
44 this.cities.addAll(cities);
45 }
46
47 public void run() {
48
49 ClientBootstrap bootstrap = new ClientBootstrap(
50 new NioClientSocketChannelFactory(
51 Executors.newCachedThreadPool(),
52 Executors.newCachedThreadPool()));
53
54
55 bootstrap.setPipelineFactory(new LocalTimeClientPipelineFactory());
56
57
58 ChannelFuture connectFuture =
59 bootstrap.connect(new InetSocketAddress(host, port));
60
61
62 Channel channel = connectFuture.awaitUninterruptibly().getChannel();
63
64
65 LocalTimeClientHandler handler =
66 channel.getPipeline().get(LocalTimeClientHandler.class);
67
68
69 List<String> response = handler.getLocalTimes(cities);
70
71 channel.close().awaitUninterruptibly();
72
73
74 bootstrap.releaseExternalResources();
75
76
77 Iterator<String> i1 = cities.iterator();
78 Iterator<String> i2 = response.iterator();
79 while (i1.hasNext()) {
80 System.out.format("%28s: %s%n", i1.next(), i2.next());
81 }
82 }
83
84 public static void main(String[] args) throws Exception {
85
86 if (args.length < 3) {
87 printUsage();
88 return;
89 }
90
91
92 String host = args[0];
93 int port = Integer.parseInt(args[1]);
94 Collection<String> cities = parseCities(args, 2);
95 if (cities == null) {
96 return;
97 }
98
99 new LocalTimeClient(host, port, cities).run();
100 }
101
102 private static void printUsage() {
103 System.err.println(
104 "Usage: " + LocalTimeClient.class.getSimpleName() +
105 " <host> <port> <continent/city_name> ...");
106 System.err.println(
107 "Example: " + LocalTimeClient.class.getSimpleName() +
108 " localhost 8080 America/New_York Asia/Seoul");
109 }
110
111 private static List<String> parseCities(String[] args, int offset) {
112 List<String> cities = new ArrayList<String>();
113 for (int i = offset; i < args.length; i ++) {
114 if (!args[i].matches("^[_A-Za-z]+/[_A-Za-z]+$")) {
115 System.err.println("Syntax error: '" + args[i] + "'");
116 printUsage();
117 return null;
118 }
119 cities.add(args[i].trim());
120 }
121 return cities;
122 }
123 }