如果服務器是遠程的(與客戶端不在同一臺機器上),我很困惑客戶端如何連接到服務器。我的代碼使用本地主機工作正常,但我無法弄清楚客戶端如何實際連接到服務器主機,以便它查找rmiregistry。我很困惑什麼被存儲在服務器的註冊表中,是Sample還是localhost?這可能是愚蠢的,但我試圖將localhost轉換爲其在客戶端的ipaddress,並做String url =「//」+ server +「:」+ 1099 +「/ Sample」;其中服務器是來自getbyname()的ip,但我得到一個異常:java.rmi.NotBoundException:127.0.0.1:1099/Sample 這是兩臺機器上的客戶端和服務器。我只是想弄清楚兩者如何遠程連接,但它甚至不能使用localhost的ip地址在同一臺機器上工作。連接客戶端服務器RMI
客戶:
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class SampleClient {
public static void main(String args[]) {
String url = "//" + "localhost" + ":" + 1099 + "/Sample";
SampleInterface sample = (SampleInterface)Naming.lookup(url);
} catch(Exception e) {
System.out.println("SampleClient exception: " + e);
}
}
}
服務器:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
public class SampleServer {
public static void main(String args[]) throws IOException {
// Create and install a security manager
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try {
String url = "//localhost:" + 1099 + "/Sample";
System.out.println("binding " + url);
Naming.rebind(url, new Sample());
// Naming.rebind("Sample", new Sample());
System.out.println("server " + url + " is running...");
}
catch (Exception e) {
System.out.println("Sample server failed:" + e.getMessage());
}
}
}