1
2
3
4
5
6
7
8
9
10
11
12
13
14 package chapters.mdc;
15
16 import java.io.BufferedReader;
17 import java.io.InputStreamReader;
18 import java.rmi.Naming;
19 import java.rmi.RemoteException;
20
21
22
23
24
25
26
27 public class NumberCruncherClient {
28 public static void main(String[] args) {
29 if (args.length == 1) {
30 try {
31 String url = "rmi://" + args[0] + "/Factor";
32 NumberCruncher nc = (NumberCruncher) Naming.lookup(url);
33 loop(nc);
34 } catch (Exception e) {
35 e.printStackTrace();
36 }
37 } else {
38 usage("Wrong number of arguments.");
39 }
40 }
41
42 static void usage(String msg) {
43 System.err.println(msg);
44 System.err.println("Usage: java chapters.mdc.NumberCruncherClient HOST\n" + " where HOST is the machine where the NumberCruncherServer is running.");
45 System.exit(1);
46 }
47
48 static void loop(NumberCruncher nc) {
49 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
50 int i = 0;
51
52 while (true) {
53 System.out.print("Enter a number to factor, '-1' to quit: ");
54
55 try {
56 i = Integer.parseInt(in.readLine());
57 } catch (Exception e) {
58 e.printStackTrace();
59 }
60
61 if (i == -1) {
62 System.out.print("Exiting loop.");
63
64 return;
65 } else {
66 try {
67 System.out.println("Will attempt to factor " + i);
68
69 int[] factors = nc.factor(i);
70 System.out.print("The factors of " + i + " are");
71
72 for (int k = 0; k < factors.length; k++) {
73 System.out.print(" " + factors[k]);
74 }
75
76 System.out.println(".");
77 } catch (RemoteException e) {
78 System.err.println("Could not factor " + i);
79 e.printStackTrace();
80 }
81 }
82 }
83 }
84 }