RemoteTime.idl)module RemoteTime {
interface ExactTime {
string getTime();
};
};
module 對應 Java 套件interface 映射為 Java 介面idltojava -fserver -fclient RemoteTime.idl
產出關鍵檔案:
RemoteTime/ExactTime.java — 客戶/伺服器共用介面RemoteTime/_ExactTimeImplBase.java — 伺服器端繼承基類 (POA 骨架)RemoteTime/_ExactTimeStub.java — 客戶端存根RemoteTime/ExactTimeHelper.java — 窄化轉換工具// Servant 實現
class ExactTimeServer extends _ExactTimeImplBase {
public String getTime() {
return DateFormat.getTimeInstance(DateFormat.FULL)
.format(new Date(System.currentTimeMillis()));
}
}
// 主程式:啟動 ORB、註冊命名服務、等待請求
public class RemoteTimeServer {
public static void main(String[] args) {
try {
ORB orb = ORB.init(args, null);
// 建立並連接 Servant
ExactTimeServer servant = new ExactTimeServer();
orb.connect(servant);
// 獲取命名服務根上下文
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// 綁定名稱 "ExactTime"
NameComponent nc = new NameComponent("ExactTime", "");
NameComponent[] path = {nc};
ncRef.rebind(path, servant);
System.out.println("Time Server ready...");
// 阻塞主執行緒
synchronized(new Object()) { while(true) wait(); }
} catch (Exception e) { e.printStackTrace(); }
}
}
public class RemoteTimeClient {
public static void main(String[] args) {
try {
ORB orb = ORB.init(args, null);
// 解析命名服務
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// 查找物件引用
NameComponent nc = new NameComponent("ExactTime", "");
NameComponent[] path = {nc};
ExactTime timeRef = ExactTimeHelper.narrow(ncRef.resolve(path));
// 遠程調用
String exactTime = timeRef.getTime();
System.out.println("Current time: " + exactTime);
} catch (Exception e) { e.printStackTrace(); }
}
}
tnameserv -ORBInitialPort 900 # 預設埠 900
java -classpath . RemoteTimeServer -ORBInitialPort 900 -ORBInitialHost localhost
java -classpath . RemoteTimeClient -ORBInitialPort 900 -ORBInitialHost localhost
Helper.narrow() 將通用 org.omg.CORBA.Object 安全轉為具體介面COMM_FAILURE:檢查防火牆、ORB 埠、主機名解析OBJECT_NOT_EXIST:命名服務未啟動、綁定名稱錯誤、伺服器未註冊MARSHAL:IDL/存根版本不一致,重新編譯部署本範例展示了 CORBA 最核心的「IDL 定義 → 編譯映射 → 命名服務註冊/查找 → 遠程調用」完整閉環。Java IDL (JDK 內建) 提供零成本入門體驗,生產級系統建議採用高效能商用 ORB (VisiBroker, Orbix, OpenORB) 並配置持久 POA、負載均衡、安全傳輸 (SSLIOP) 等企業級特性。