天天看點

java RMI 分布式簡單應用

PersonService.java

<span style="font-size:14px;">import java.rmi.*;
import java.util.*;

 
public interface PersonService extends Remote
{
	public List<Person> GetList() throws RemoteException;
}
</span>
           

PersonServiceImpl.java

<span style="font-size:14px;">import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.LinkedList;
import java.util.List;



class  PersonServiceImpl extends UnicastRemoteObject implements PersonService
{
	public PersonServiceImpl() throws RemoteException {
	super();
	}

	public List<Person> GetList() throws RemoteException {

	System.out.println("Get Person Start!");
	List<Person> personList=new LinkedList<Person>();

	Person person1=new Person();
	person1.setAge(25);
	person1.setId(0);
	person1.setName("Leslie");
	personList.add(person1);

	Person person2=new Person();
	person2.setAge(25);
	person2.setId(1);
	person2.setName("Rose");
	personList.add(person2);

	return personList;
	} 

}
</span>
           

Person.java

<span style="font-size:14px;">import java.io.Serializable;

class  Person implements Serializable
{
	private int id;
	private String name;
	private int age;


    public void setId(int id) {
	this.id = id;
	}

	public int getId() {
	return id;
	}

	public void setName(String name) {
	this.name = name;
	}

	public String getName() {
	return name;
	}

	public void setAge(int age) {
	this.age = age;
	}

	public int getAge() {
	return age;
	}

}
</span>
           

Program.java

<span style="font-size:14px;">import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

class  Program
{
	public static void main(String[] args) 
	{
		try {
		PersonService personService=new PersonServiceImpl();
		//注冊通訊端口
		LocateRegistry.createRegistry(6600);
		//注冊通訊路徑
		Naming.rebind("rmi://192.168.199.195:6600/PersonService", personService);
		System.out.println("Service Start!");
		} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
	}
}
</span>
           

Client.java

<span style="font-size:14px;">import java.rmi.Naming;
import java.util.List;


class  Client
{
	public static void main(String[] args) 
	{
		try{
		//調用遠端對象,注意RMI路徑與接口必須與伺服器配置一緻
		PersonService personService=(PersonService)Naming.lookup("rmi://192.168.199.195:6600/PersonService");
		List<Person> personList=personService.GetList();
		for(Person person:personList){
		System.out.println("ID:"+person.getId()+" Age:"+person.getAge()+" Name:"+person.getName());
		}
		}catch(Exception ex){
		ex.printStackTrace();
		}
	}
}
</span>
           

(5).運作和調用

● 在伺服器上執行Program

D:\RMISample\server>java Program

● 在本地客戶機上運作Client

D:\RMISample\client>java Client

● 在遠端客戶機上運作HelloClient(須指明RMI伺服器主機名或IP位址)

java HelloClient 222.222.34.34

上面代碼成功解決了  --->    java RMI問題.兩台電腦測試的時候遇到問題