RMI简单示例
程序员文章站
2022-03-21 14:20:24
...
一、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(); } }
上一篇: matplotlib绘图入门及常用
下一篇: matplotlib绘图的几种方式