2013-10-30 325 views
0

如果服务器是远程的(与客户端不在同一台机器上),我很困惑客户端如何连接到服务器。我的代码使用本地主机工作正常,但我无法弄清楚客户端如何实际连接到服务器主机,以便它查找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()); 
     } 
    } 
} 

回答

1

服务器应该绑定到 'localhost' 的运行注册表。

客户端应在服务器主机上查找注册表。

就这么简单。

我很困惑什么被存储在服务器的注册表中,它是Sample还是localhost?

都没有。你混淆了三种不同的东西:

  1. 主机名,在本例中为'localhost'。
  2. 绑定名称,在本例中为'Sample'。
  3. 绑定的对象,即远程存根。
相关问题