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