您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Java远程方法调用(RMI)允许在一个Java虚拟机(JVM)上的对象调用另一个JVM上的子类方法
java.rmi.Remote
接口,并为每个要远程调用的方法声明抛出java.rmi.RemoteException
异常。import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteInterface extends Remote {
String sayHello() throws RemoteException;
}
RemoteException
异常。import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class RemoteImplementation extends UnicastRemoteObject implements RemoteInterface {
public RemoteImplementation() throws RemoteException {
super();
}
@Override
public String sayHello() throws RemoteException {
return "Hello from remote implementation!";
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
RemoteInterface remoteObject = new RemoteImplementation();
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("RemoteInterface", remoteObject);
System.out.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
RemoteInterface remoteObject = (RemoteInterface) registry.lookup("RemoteInterface");
String result = remoteObject.sayHello();
System.out.println("Result from server: " + result);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
在这个例子中,客户端通过RMI注册表查找名为"RemoteInterface"的远程对象,并调用其sayHello()
方法。远程对象在服务器上实现,并通过RMI注册表暴露给客户端。这样,客户端就可以像调用本地对象一样调用远程对象的方法,实现了跨JVM的远程方法调用。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。