读书人

RMI远程调用的跨平台应用Demo

发布时间: 2012-07-08 17:43:43 作者: rapoo

RMI远程调用的跨平台使用Demo
最近项目中用到了RMI 粗略的学习了一下,写了一个跨平台远程调用的demo,供初学者参考!

声明远程调用接口,接口要继承Remote,并且每个接口方法都要抛出RemoteException异常,代码如下:

import java.rmi.Remote;import java.rmi.RemoteException;public interface IRMITest extends Remote {    public String sayHello (String name) throws RemoteException ;}

接口方法的实现:
import java.net.MalformedURLException;import java.rmi.RemoteException;import java.rmi.registry.LocateRegistry;import java.rmi.registry.Registry;import java.rmi.server.UnicastRemoteObject;import com.rmi.inf.IRMITest;@SuppressWarnings("serial")public class RMITestImpl extends UnicastRemoteObject implements IRMITest {public RMITestImpl() throws RemoteException{}@Overridepublic String sayHello(String name) throws RemoteException {System.out.println("test()方法被远程调用:   hello ," + name);return "hello," + name + "-------successful";}}

将实现接口生成的stub的文件和接口打成jar包,供客户端使用

服务器端:
import java.net.MalformedURLException;import java.rmi.RemoteException;import java.rmi.registry.LocateRegistry;import java.rmi.registry.Registry;public class RMIServer {public static void main(String[] args) throws MalformedURLException {try {System.setProperty("java.rmi.server.hostname", "192.168.1.159");String rootpath= Thread.currentThread().getContextClassLoader().getResource("").toString();System.setProperty("java.rmi.server.codebase", rootpath);Registry registry = LocateRegistry.createRegistry(5858); RMITestImpl testImpl = new RMITestImpl();registry.rebind("hello", testImpl);System.out.println("server is ready");} catch (RemoteException e) {e.printStackTrace();}}}

客户端:
public class RMITestClient {public static void main(String[] args) {try {//在客户端加载策略文件        System.setProperty ("java.security.policy", "security.policy");        System.setSecurityManager(new RMISecurityManager());IRMITest test = (IRMITest)Naming.lookup("rmi://192.168.1.159:5858/hello");System.out.println("调用远程方法:" + test.sayHello("world"));} catch (MalformedURLException e) {e.printStackTrace();} catch (RemoteException e) {e.printStackTrace();} catch (NotBoundException e) {e.printStackTrace();}}}


策略文件
grant {permission java.net.SocketPermission "*:1099-65535", "connect,accept,resolve";};


读书人网 >行业软件

热点推荐