您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。