2012-10-18 45 views
0

我正在编写一个程序,使用RMI将客户机连接到服务器,到目前为止,我一直在收到java.net.ConnectException: Connection refused使用Java RMI建立连接

这是我的代码;

接口

public interface ServerInterface extends Remote 
{ 
public String getMessage() throws RemoteException; 

} 

服务器

public class Server extends UnicastRemoteObject implements ServerInterface 
{ 
int portNumber = 7776; 
String ipAddress; 
Registry registry; 

public Server() throws RemoteException 
{ 
    try 
    { 
     ipAddress = "192.168.0.104"; 
     System.out.println("IP Address: " + ipAddress + " Port Number: " + portNumber); 
     registry = LocateRegistry.getRegistry(); 
     registry.rebind("ServerFour", this); 
    } 
    catch (RemoteException e) 
    { 
     System.out.println("Remote Exception Error"); 
    } 
} 

public String getMessage() throws RemoteException 
{ 
    String output = "Connected to Server"; 

    return output; 
} 

public static void main(String args[]) 
{ 
    try 
    { 
     Server server = new Server(); 

    } 
    catch (RemoteException ex) 
    { 
     System.out.println("Remote Exception in Main"); 
    } 

} 

} 

客户

​​

现在我只想客户端上的ServerInterface方法调用,并打印出它的消息,但我似乎无法得到它的工作。当我启动客户端时,出现上面显示的异常消息。

当我启动服务器它返回:

IP地址:client4/127.0.1.1端口号:1234

更新:

我已经改变了端口号7776 冉rmiregistry的7776 &

这是我所得到的,当我启动服务器和运行netstat -anpt http://i.imgur.com/GXnnG.png

现在在客户端上我得到这样的: http://i.imgur.com/aBvW3.png

+2

防火墙服务器上的阻塞端口1234?你可以telnet服务吗? –

+0

它做同样的事情。 – Nick

+0

请澄清“它做同样的事情”。如果您使用telnet拒绝连接?然后服务器没有启动并运行,或者访问被禁止。 –

回答

0

似乎RMI Registry势必localhost(参见127.0.0.1 - 我认为127.0.1.1是一个拼写错误?),但是尝试从192.168.0.104的客户端联系它 - 这是行不通的,因为没有什么可以在该接口上进行监听!尝试将客户serverAddress更改为127.0.0.1

命令netstat -anpt(或在Windows上:netstat -anbt)是你的朋友,当你想知道哪些接口绑定了哪些进程时(t用于TCP)。

这是注册表绑定到特定IP(如:localhost)的方式,

registry = 
    LocateRegistry. 
     createRegistry(portNumber , 
         new RMIClientSocketFactory() 
         { 
          @Override 
          public Socket createSocket(String host, int port) throws IOException 
          { 
           return new Socket("127.0.0.1" , port); 
          } 
         } , 
         new RMIServerSocketFactory() 
         { 
          @Override 
          public ServerSocket createServerSocket(int port) throws IOException 
          { 
           return new ServerSocket(port , 0 , InetAddress.getByName("localhost")); 
          } 
         }); 

干杯,

+0

不正确。他不是'将服务器绑定到本地主机'。他将远程对象绑定到本地主机上运行的RMI注册表,该注册表是唯一可以绑定到的注册表。这与ServerSocket的绑定地址无关,默认为0.0.0.0,除非您指定一个RMIServerSocketFactory执行其他操作,他还没有完成。他的代码是正确的。 – EJP

+0

我的表述非常通用 - 道歉 - 我已经编辑了一些答案。这是正确的你说,但它似乎是注册表绑定到本地主机(“IP地址:client4/127.0.1.1端口号:1234”),所以我认为我的建议仍然有效。 –

+0

不需要。注册表是使用端口号创建的,没有主机地址,所以它被绑定到0.0.0.0,就像上面一样。该程序仅仅是打印localhost的值:这并不是证明什么是绑定的。 – EJP