rmi调用一般过程:
接口:
package com.zhang.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* 实现Remote接口,定义的方法都需要抛出RemoteException
* <p />
*
* @author Administrator
*/
public interface TestRmiInterface extends Remote {
String concat(String a, String b) throws RemoteException;
}
实现类:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* 继承UnicastRemoteObject类,实现TestRmiInterface接口
* <p />
*
* @author Administrator
*/
public class TestRmiImpl extends UnicastRemoteObject implements TestRmiInterface {
private static final long serialVersionUID = 7060916499195401961L;
/**
* 显式定义构造方法,需要抛出RemoteExcepiton
*
* @throws RemoteException
*/
protected TestRmiImpl() throws RemoteException {
super();
}
/**
* {@inheritDoc}
*/
@Override
public String concat(String a, String b) {
//System.out.println(a+b);
return a + b;
}
}
服务器端:
package com.zhang.rmi;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public Server(){
TestRmiInterface testRmi = null;
Registry registry = null;
try {
registry = LocateRegistry.createRegistry(1099);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
testRmi = new TestRmiImpl();
registry.rebind("rmi://localhost:1099/testServer", testRmi);
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public static void main(String[] args) {
// if(System.getSecurityManager() == null){
// System.out.println("SecurityManager is null");
// System.setSecurityManager(new RMISecurityManager());
// }
new Server();
System.out.println("server ready");
}
}
客户端:
package com.zhang.rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry(1099);
TestRmiInterface testRmi = (TestRmiInterface) registry.lookup("rmi://localhost:1099/testServer");
String test = testRmi.concat("hello", "rmi");
System.out.println(test);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}