我试图在客户端运行此程序,但我不明白它是如何在服务器端运行,并不运行客户端 .
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Interface extends Remote{
void guessNumber() throws RemoteException;
}
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Implement implements Interface{
@Override
public void guessNumber() {
System.out.println("RMI server is running...");
int number;
int guess;
Random random = new Random();
number = random.nextInt(20)+1;
guess = random.nextInt(20)+1;
System.out.println("Server guess the number!");
while(number != guess) {
if (number > guess) {
System.out.println("Client:" + guess);
System.out.println("Guess a greater number:");
guess = random.nextInt(guess)+(20-guess-1);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (number < guess) {
System.out.println("Client:" + guess);
System.out.println("Guess a smaller number:");
guess = random.nextInt(guess)+1;
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("Correct number is: " + number);
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server extends Implement{
public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
Implement obj = new Implement();
// Exporting the object of implementation class
// (here we are exporting the remote object to the stub)
Interface stub = (Interface) UnicastRemoteObject.exportObject(obj, 0);
// Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Interface", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
// Looking up the registry for the remote object
Interface stub = (Interface) registry.lookup("Interface");
// Calling the remote method using the obtained object
stub.guessNumber();
// System.out.println("Remote method invoked");
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}