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";}}
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";};