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