一个简单rmi例子。
1、当前编译后的class在bin目录下
2、注册:开一个cmd,到bin目录下运行“rmiregistry”
3、生成stub和skel的class文件:开一个cmd,到bin目录下运行“rmic -vcompat com.rmi.CalculatorImpl”
4、编写授权文件policy.txt
5、启动服务器:开一个cmd,到bin目录下运行“java -Djava.security.policy=com.rmi.policy.txt com.rmi.Ca
culatorServer”
6、运行客户端:开一个cmd,到bin目录下运行“D:\workspace\demo\bin>java -Djava.security.policy=com.rmi.policy.txt com.rmi.Cal
culatorClient”
package com._rmi;
import java.rmi.Remote;
public interface Calculator extends Remote {
public long add(long a, long b) throws java.rmi.RemoteException;
public long sub(long a, long b) throws java.rmi.RemoteException;
public long mul(long a, long b) throws java.rmi.RemoteException;
public long div(long a, long b) throws java.rmi.RemoteException;
}
package com._rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class CalculatorImpl extends UnicastRemoteObject implements Calculator {
public CalculatorImpl() throws RemoteException
{
super();
}
@Override
public long add(long a, long b) throws RemoteException {
// TODO Auto-generated method stub
return a+b;
}
@Override
public long div(long a, long b) throws RemoteException {
// TODO Auto-generated method stub
return a/b;
}
@Override
public long mul(long a, long b) throws RemoteException {
// TODO Auto-generated method stub
return a*b;
}
@Override
public long sub(long a, long b) throws RemoteException {
// TODO Auto-generated method stub
return a-b;
}
}
package com._rmi;
import java.rmi.Naming;
public class CalculatorServer {
public CalculatorServer()
{
try
{
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
}
catch(Exception e)
{
System.out.println(e);
}
}
/**
* @param args
*/
public static void main(String[] args) {
new CalculatorServer();
}
}
package com._rmi;
import java.rmi.Naming;
public class CalculatorClient {
/**
* @param args
*/
public static void main(String[] args) {
try {
Calculator c = (Calculator) Naming
.lookup("rmi://localhost/CalculatorService");
System.out.println( c.add(1,2) );
System.out.println( c.sub(1,2) );
System.out.println( c.mul(1,2) );
System.out.println( c.div(1,2) );
} catch (Exception e) {
e.printStackTrace();
}
}
}