2012-02-16 82 views
2

我寫了一個簡單的客戶端 - 服務器對,發送一個對象給服務器。我已經測試了代碼,它的工作原理是,我使用LOCALHOST作爲服務器名稱。對Java中的客戶端服務器IP配置不確定

當試圖使用我自己的IP地址連接到服務器時,客戶端連續超時。我不禁想到我錯過了一個竅門,如果有人可以看看我將非常感激的代碼。非常感謝,J.

客戶

ObjectOutputStream oos = null; 
    ObjectInputStream ois = null; 
    Socket socket = null; 
    Person p = null; 

    try { 
    // My IP address entered here.. 
    socket = new Socket("xx.xx.xxx.xxx", 3000); 
    // open I/O streams for objects 
    oos = new ObjectOutputStream(socket.getOutputStream()); 
    ois = new ObjectInputStream(socket.getInputStream()); 


    /* 
    // read an object from the server 
    p = (Person) ois.readObject(); 
    System.out.print("Name is: " + p.getName()); 
    oos.close(); 
    ois.close();*/ 

    //write object to the server 
    // p = new Person("HAL"); 
    oos.writeObject(new Person("HAL")); 
    oos.flush(); 
    ois.close(); 
    oos.close(); 

    } catch(Exception e) { 
    System.out.println(e.getMessage()); 
    } 

服務器

public Server() throws Exception { 
server = new ServerSocket(3000); 
System.out.println("Server listening on port 3000."); 
this.start(); 

}

回答

2

要麼你需要讓你的服務器結合0.0.0.0(通配符,你的機器上所有接口)或您希望它監聽的特定IP。你只用ServerSocket構造需要一個端口號,並結合localhost這是要解決到127.0.0.1

server = new ServerSocket(3000, 5, InetAddress.getByName("0.0.0.0")); 

編輯補充:第二paramater是積壓大小。這是在額外的連接嘗試將導致「連接被拒絕」之前,可以排隊等待您的連接數量爲accept()

+0

嗨布賴恩,感謝您的迴應,幫助我瞭解過程。但是,使用上述服務器構造函數時連接仍然超時。我甚至試圖將InetAddress設置爲我的IP,但在編譯時給了我一個Bind Exception。 – Jnanathan 2012-02-16 15:59:47

+0

你是否在你的家用電腦上使用路由器?上面的代碼在我的機器上完美工作。如果你可以發佈堆棧跟蹤,我可以幫忙。 – 2012-02-16 16:02:07

+0

是的。我正在關閉正在工作的計算機上的防火牆。很奇怪,自從上次回覆以來,我嘗試了大約12次。它只是曾經工作過。 – Jnanathan 2012-02-16 16:07:17