RMI使用

2018-04-27  本文已影响18人  背麻袋的袋鼠
注意事项

1.服务接口要继承java.rmi.Remote接口,声明方法必须 throws
java.rmi.RemoteException,否则会抛异常
2.接口实现类继承UnicastRemoteObject类,构造方法需要throws RemoteException,同时将实现类声明为public
3.实现类最好实现Serializable接口,实现方法中throws java.rmi.RemoteException

代码收藏
======================interface============================
public interface RomTest extends Remote {
String RMI_NAME = "rmi.test.service";
public void say() throws RemoteException;
}
==========================Impl=============================
 public class RomTestImpl extends UnicastRemoteObject implements RomTest, Serializable {
protected RomTestImpl() throws RemoteException {
    super();
}
@Override
public void say(){
    System.out.println("hahha");
}
}
==========================server============================
public class TestServer {
public static void main(String[] args) {
    try {
        RomTest r = new RomTestImpl();
        //注册远程服务对象
        Registry registry = LocateRegistry.createRegistry(10002);
        try {
            try {
                Naming.bind("rmi://127.0.0.1:10002/" + RomTest.RMI_NAME, r);
            } catch (AlreadyBoundException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
}
==========================client===========================
public class TestClient {
public static void main(String[] args){
    try {
        RomTest ms = (RomTest) Naming.lookup("rmi://12.128.11.100:10002/"+RomTest.RMI_NAME);
        ms.say();
    } catch (NotBoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
  }
上一篇下一篇

猜你喜欢

热点阅读