1)首先需要一个接口,这个接口必须继承Remote接口,并编写需要实现的方法,而且这个方法必须抛出RemoteException,程序如下:
package com.mingyangnet.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RmiLogin extends Remote {
public boolean login(String userName, String password)
throws RemoteException;
}
2)再写个上面接口的实现类,这个类在实现接口的同事还要继承UnicastRemoteObject,程序如下:
package com.mingyangnet.rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
@SuppressWarnings("serial")
public class RmiLoginImpl extends UnicastRemoteObject implements RmiLogin {
protected RmiLoginImpl() throws RemoteException {
super();
}
public boolean login(String userName, String password)
throws RemoteException {
if ("admin".equals(userName) && "pass".equals(password)) {
return true;
}
return false;
}
}
3),接下来就是写个远程调用的服务器类,其中里面的端口号可以随便填写,只要系统没有暂用就可以,最好是1024之后的数字,程序如下:
package com.mingyangnet.rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class RmiServer {
/**
* @param args
*/
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(8080);
RmiLogin login = new RmiLoginImpl();
Naming.rebind("//localhost:8080/rmiserver", login);
System.out.println("Server is listening...");
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
4),最后就是写个客户端的程序去实现登陆的功能。
package com.mingyangnet.rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class RmiClient {
/**
* @param args
*/
public static void main(String[] args) {
try {
String url = "//localhost:8080/rmiserver";
RmiLogin login = (RmiLogin)Naming.lookup(url);
System.out.println("client is connecting...");
System.out.println(login.login("admin", "pass"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
这个是简单的的rmi调用的程序,旨在说明rmi调用的流程和原理。