50,639
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
package org.ngweb.rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* The implementation class of the remote method defined in interface
*
* @author Huangng
*
*/
public class Rmi extends UnicastRemoteObject implements RmiInterface {
private static final long serialVersionUID = 1L;
// The constructor have to throw RemoteException
public Rmi() throws RemoteException {
}
// The implemented remote method.
public String say(String name) throws RemoteException {
System.out.println("Called by HelloClient");
return "Hello, " + name;
}
}
package org.ngweb.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* An interface that define the remote method, which should be in both server
* and client end.
*
* @author Huangng
*
*/
public interface RmiInterface extends Remote {
// Any remote method have to throw RemoteException
public String say(String name) throws RemoteException;
}
package org.ngweb.rmi;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
/**
*
* Java RMI server
*
* @author Huangng
*
*/
public class RmiServer {
public static void main(String[] argv) {
try {
// set port number to 1099
LocateRegistry.createRegistry(1099);
// The instance of class with remote method
RmiInterface hello = new Rmi();
// Register the instance
Naming.rebind("Hello", hello);
System.out.println("Starting RMI Server success.");
} catch (Exception e) {
System.out.println("Starting RMI Server failed: " + e);
}
}
}
package org.ngweb.rmi;
import java.rmi.Naming;
/**
*
* A client end of Java RMI
*
* @author Huangng
*
*/
public class RmiClient {
public static void main(String[] argv) {
try {
// Find an instance of Hello in remote machine
RmiInterface hello = (RmiInterface) Naming
.lookup("//127.0.0.1:1099/Hello");
// Call remote method
System.out.println(hello.say("huang"));
} catch (Exception e) {
System.out.println("RMI Client exception: " + e);
}
}
}
package org.ngweb.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* An interface that define the remote method, which should be in both server
* and client end.
*
* @author Huangng
*
*/
public interface RmiInterface extends Remote {
// Any remote method have to throw RemoteException
public String say(String name) throws RemoteException;
}