1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.factorial;
17
18 import java.net.InetSocketAddress;
19 import java.util.concurrent.Executors;
20
21 import org.jboss.netty.bootstrap.ClientBootstrap;
22 import org.jboss.netty.channel.Channel;
23 import org.jboss.netty.channel.ChannelFuture;
24 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
25
26
27
28
29
30 public class FactorialClient {
31
32 private final String host;
33 private final int port;
34 private final int count;
35
36 public FactorialClient(String host, int port, int count) {
37 this.host = host;
38 this.port = port;
39 this.count = count;
40 }
41
42 public void run() {
43
44 ClientBootstrap bootstrap = new ClientBootstrap(
45 new NioClientSocketChannelFactory(
46 Executors.newCachedThreadPool(),
47 Executors.newCachedThreadPool()));
48
49
50 bootstrap.setPipelineFactory(new FactorialClientPipelineFactory(count));
51
52
53 ChannelFuture connectFuture =
54 bootstrap.connect(new InetSocketAddress(host, port));
55
56
57 Channel channel = connectFuture.awaitUninterruptibly().getChannel();
58
59
60 FactorialClientHandler handler =
61 (FactorialClientHandler) channel.getPipeline().getLast();
62
63
64 System.err.format(
65 "Factorial of %,d is: %,d", count, handler.getFactorial());
66
67
68 bootstrap.releaseExternalResources();
69 }
70
71 public static void main(String[] args) throws Exception {
72
73 if (args.length != 3) {
74 System.err.println(
75 "Usage: " + FactorialClient.class.getSimpleName() +
76 " <host> <port> <count>");
77 return;
78 }
79
80
81 String host = args[0];
82 int port = Integer.parseInt(args[1]);
83 int count = Integer.parseInt(args[2]);
84 if (count <= 0) {
85 throw new IllegalArgumentException("count must be a positive integer.");
86 }
87
88 new FactorialClient(host, port, count).run();
89 }
90 }