RMI使用中

启动RMI注册并注册远程对象时的注意事项:

可以使用如下两种方式

LocateRegistry.createRegistry(51099);
  try {
   Naming.rebind("//localhost:51099/TalkServer", remote);
  } catch (Exception e) {
   e.printStackTrace();
  }

 

 

 

 

Registry re=LocateRegistry.createRegistry(51099);
  try {
   re.rebind("TalkServer", remote);
  } catch (Exception e) {
   e.printStackTrace();
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java RMI(Remote Method Invocation)是 Java 实现远程方法调用的一种机制,它允许一个 Java 程序从另一个 Java 程序调用对象。下面是一个简单的 Java RMI 的示例: 1. 定义接口 首先需要定义一个接口,用于客户端和服务端之间进行通信。比如: ``` public interface MyInterface extends Remote { public String sayHello() throws RemoteException; } ``` 这里的 MyInterface 继承了 Remote 接口,表示这个接口是一个远程接口。 2. 实现接口 接下来需要在服务端实现这个接口,比如: ``` public class MyInterfaceImpl extends UnicastRemoteObject implements MyInterface { public MyInterfaceImpl() throws RemoteException { super(); } public String sayHello() throws RemoteException { return "Hello, world!"; } } ``` 这里的 MyInterfaceImpl 类实现了 MyInterface 接口,并继承了 UnicastRemoteObject 类。这个类的构造函数需要抛出 RemoteException 异常。 3. 注册服务 在服务端需要将 MyInterfaceImpl 的实例注册到 RMI registry ,比如: ``` MyInterface myInterface = new MyInterfaceImpl(); Registry registry = LocateRegistry.getRegistry(); registry.bind("MyInterface", myInterface); ``` 这里使用了 LocateRegistry.getRegistry() 方法获取 RMI registry 的引用,然后使用 registry.bind() 方法将 MyInterfaceImpl 的实例注册到 RMI registry 。 4. 调用服务 在客户端需要获取 MyInterfaceImpl 的实例并调用它的方法,比如: ``` Registry registry = LocateRegistry.getRegistry("localhost"); MyInterface myInterface = (MyInterface) registry.lookup("MyInterface"); String result = myInterface.sayHello(); System.out.println(result); ``` 这里使用了 registry.lookup() 方法获取 MyInterfaceImpl 的实例,然后调用它的 sayHello() 方法并输出结果。 需要注意的是,使用 RMI 调用远程方法时,可能会抛出 RemoteException 异常,需要进行处理。此外,还需要在客户端和服务端都使用相同的接口和实现类,以保证通信的正确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值