使用RMI(远程方法调用)可以简化客户端与服务端之间的交互过程,当客户端在与服务端交互时,就感觉像是客户端在调用本地的方法
实现步骤:
- 要实现RMI,必须要定义一个接口,该接口继承自import java.rmi.Remote类;在该类中声明服务端提供的方法,每一个方法必须是静态的并且每个方法后应该要
有throws RemoteException的声明,如下:
public interface SevFun extends Remote {
public boolean checkpassword(int idnum,String key) throws RemoteException;
public int genxing(int idnum,int sco) throws RemoteException;
public int zhuce(int idnum, String pas) throws RemoteException;
public int chaxun(int idnum) throws RemoteException;
public int shanchu(int idnum) throws RemoteException;
public int[] startGame() throws RemoteException;
public double checkresult(String str) throws RemoteException;
public int[][] chaxunqianshi() throws RemoteException ;
public int [] checkIDqianshi() throws RemoteException ;
public int [] checkScoreqianshi() throws RemoteException;
}
- 定义一个类继承在上一步我们所写的接口,在该类中重写接口中的方法实现我们需要的功能,如下:
public class database extends UnicastRemoteObject implements SevFun{
protected database() throws RemoteException {
super();
}
//验证密码:
public boolean checkpassword(int idnum,String pas)
{
String password = " ";
String sql = "select Password from Vincenttest.kcsj where ID = '"+idnum+"'";
try {
Statement sta = test01.getconnection().createStatement();
ResultSet rs = sta.executeQuery(sql);
while(rs.next()){
password = rs.getString("Password"); //在次数根据ID获取相应的密码;
}
} catch (SQLException e) {
e.printStackTrace();
}
//在此数将输入的密码与数据库中得密码进行比较
if(pas.equals(password))
{
return true ;
}
else
{
return false ;
}
}
- 服务端绑定,绑定远程调用的对象,声明端口号如下:
public class Sever {
SevFun severefun;
public void ser() throws RemoteException, MalformedURLException, AlreadyBoundException {
severefun = new database();
LocateRegistry.createRegistry(8888);
Naming.bind("rmi://192.168.1.101:8888/severfun",severefun);
System.out.println("服务端:对象绑定成功!");
}
public static void main(String[] args) {
try {
Sever sever = new Sever();
sever.ser();
while(true);
} catch (RemoteException | MalformedURLException | AlreadyBoundException e) {
e.printStackTrace();
}
}
}
- 客户端的远程调用:例如登录的校验
public class client {
public SevFun sevfun;
public void clien() throws MalformedURLException, RemoteException, NotBoundException {
sevfun = (SevFun) Naming.lookup("rmi://192.168.1.101:8888/severfun");
Scanner input = new Scanner(System.in);
int ID = 0;
System.out.println("请输入登录名:");
ID = input.nextInt();
System.out.println("请输入密码:");
String key = input.next();
if (sevfun.checkpassword(ID, key) ) {
System.out.println("登录成功!");
break;
}
else {
System.out.println("用户名或密码错误请重新输入!!!");
}
}
public static void main(String[] args) {
client cilen = new client();
try {
cilen.clien();
} catch (MalformedURLException | RemoteException | NotBoundException e) {
e.printStackTrace();
}
}
}