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