server

package Server;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry; import Service.Calc;
import ServiceImpl.CalcImpl; public class Server{
// 由于这里测试我们是最终用户,所以直接将异常抛给虚拟机
public static void main(String[] args) throws Exception
{
System.setSecurityManager(new RMISecurityManager()); //权限
System.setProperty("java.rmi.server.hostname","192.168.1.119"); //指定外网IP LocateRegistry.createRegistry(9000);
//System.setProperty("java.security.policy", "/home/ufo/workspace_java/RMIServer/Calc.policy");
Calc c = new CalcImpl(); Naming.rebind("rmi://192.168.1.119:9000/Calc", c); System.out.println("rmi server start ...");
}
}

  

service

package Service;

import java.rmi.*;

public interface Calc extends Remote {
public int add(int x,int y) throws RemoteException;
}

  service impl

package ServiceImpl;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject; import Service.Calc; public class CalcImpl extends UnicastRemoteObject implements Calc{ /**
*
*/
private static final long serialVersionUID = 6523564220840187253L; public CalcImpl() throws RemoteException {
super();
// TODO Auto-generated constructor stub
} @Override
public int add(int x, int y) {
// TODO Auto-generated method stub
System.out.println("add called!");
return x+y;
} }

  

client

package client;

import java.rmi.*;
import java.net.MalformedURLException;
import Service.Calc; public class Client
{
// 同样为了方便,直接异常抛出
public static void main(String[] args) throws Exception
{
System.setSecurityManager(new RMISecurityManager());
try
{
// 这里因为是在本地所以省略了地址跟协议,若在网络中的远程方法调用,需要这样写
// Converter c = (Converter)Naming.lookup("rmi://192.168.0.13/convert");
Calc c = (Calc)Naming.lookup("rmi://192.168.1.119:9000/Calc");
int rmb = c.add(10,20);
System.out.println("add result : " + rmb);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (NotBoundException e)
{
e.printStackTrace();
}
}
}

  

客户端和服务器端都需要制定 类权限文件,即启动时命令  java -Djava.security.policy=./Calc.policy   server.Server[client.Client]

Calc.policy

grant {
permission java.security.AllPermission;
};

客户端还需要有服务的接口声明

05-11 18:01