欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RMI简单示例 博客分类: 分布式 RMI分布 

程序员文章站 2024-03-15 20:41:42
...

一、HelloInterface接口

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface HelloInterface extends Remote {
	//此处定义方法需要抛出RemoteException
	public void say() throws RemoteException;
}

 

 二、接口实现类Hello

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Hello extends UnicastRemoteObject implements HelloInterface{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4495270645164980784L;
	
	private String s;

	public Hello(String s) throws RemoteException {
		super();
		this.s=s;
	}	
	
	/**
	 *	打印
	 */
	@Override
	public void say() throws RemoteException {
		System.out.println("hello: "+s);		
	}
}

 

三、服务器端

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class RMIServer implements Runnable{

	@Override
	public void run() {
		try {
			//绑定端口
			LocateRegistry.createRegistry(1099);
			HelloInterface hi = new Hello("Hello,World!");
			//进行对象绑定
			Naming.rebind("rmi://192.168.8.88:1099/H", hi);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[]args){
		try {
			//绑定端口
			LocateRegistry.createRegistry(1099);
			HelloInterface hi = new Hello("Hello,World!");
			//进行对象绑定
			Naming.rebind("rmi://192.168.8.88:1099/H", hi);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}

 

四 、客户端

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class RMIClient implements Runnable{

	@Override
	public void run() {
		try {
			//从服务器获取对象
			HelloInterface hi =   (HelloInterface) Naming.lookup("rmi://192.168.8.88:1099/H");
			//调用获取对象的方法
			hi.say();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}		
	}
	public static void main(String[]args){
		try {
			//从服务器获取对象
			HelloInterface hi =   (HelloInterface) Naming.lookup("rmi://192.168.8.88:1099/H");
			//调用获取对象的方法
			hi.say();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
	}
}

 

五、测试

import org.junit.BeforeClass;
import org.junit.Test;

import com.rmi.client.RMIClient;
import com.rmi.server.RMIServer;

public class RMITest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test
	public void testRMI() throws InterruptedException{
		RMIServer rs = new RMIServer();
		rs.run();
		Thread.sleep(100);
		RMIClient rc = new RMIClient();
		rc.run();
	}
}

 

相关标签: RMI 分布