您的位置:首页 > 其它

初识RMI基本原理

2016-09-23 21:12 106 查看
RMI分为客户端和服务器端,和socket类似。

客户端:

package it.york.rmi.client;

import it.york.rmi.stub.UserManagerInterface;

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class Entry {//客户端
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 2001);
UserManagerInterface userManager = 
(UserManagerInterface) registry.lookup("userManager");
System.out.println(""+userManager.getAdminAccount().getUsername() 

                   +"\r\n\t" +userManager.getAdminAccount().getPassword()); 
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

服务器端:

package it.york.rmi.bean;

import java.io.Serializable;

public class Account implements Serializable, Cloneable {
private static final long serialVersionUID = -1858518369668584532L; 

    private String username; 

    private String password; 

     

    public String getUsername() { 

        return username; 

    } 

    public void setUsername(String username) { 

        this.username = username; 

    } 

    public String getPassword() { 

        return password; 

    } 

    public void setPassword(String password) { 

        this.password = password; 

    } 

}

package it.york.rmi.stub;

import it.york.rmi.bean.Account;

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface UserManagerInterface extends Remote {
public String getUserName() throws RemoteException;
public Account getAdminAccount() throws RemoteException;

}

package it.york.rmi;

import it.york.rmi.stub.UserManagerInterface;

import java.rmi.AlreadyBoundException;

import java.rmi.RemoteException;

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

import java.rmi.server.UnicastRemoteObject;

public class Entry {//服务器端
public static void main(String[] args) throws AlreadyBoundException,RemoteException{
UserManagerImpl userManage = new UserManagerImpl();
UserManagerInterface userManagerInterface = //这里很重要,服务器端的对象,客户端因此能用
(UserManagerInterface) UnicastRemoteObject.exportObject(userManage,0);
Registry registry = LocateRegistry.createRegistry(2001);
registry.rebind("userManager", userManagerInterface);
System.out.println("server is ready");
}

}

package it.york.rmi;

import java.rmi.RemoteException;

import it.york.rmi.bean.Account;

import it.york.rmi.stub.UserManagerInterface;

public class UserManagerImpl implements UserManagerInterface {

private static final long serialVersionUID = -3111492742628447261L;
public UserManagerImpl() throws RemoteException{

}
public String getUserName() throws RemoteException {
// TODO Auto-generated method stub
return "york";
}

public Account getAdminAccount() throws RemoteException {
// TODO Auto-generated method stub
Account account = new Account();
account.setPassword("520666");
account.setUsername("ke.xiao");
return account;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  RMI