2012-10-18 77 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