2012-02-06 236 views
1

我正在學習使用Java通過套接字進行的客戶端服務器通信。 首先,我使用以下代碼檢索自己機器的IP地址。簡單客戶端服務器通信

InetAddress ownIP=InetAddress.getLocalHost(); 
//the result being 192.168.56.1 

現在我寫使用上述地址的簡單的客戶端服務器應用程序如下

public class SimpleClientServer { 
public static void main(String[] args) 
{ 
    //sending "Hello World" to the server 
    Socket clientSocket = null; 
    PrintWriter out = null; 
    BufferedReader in = null; 

    try 
    { 

     clientSocket = new Socket("192.168.56.1", 16000); 

     out = new PrintWriter(clientSocket.getOutputStream(), true); 

     in = new BufferedReader(new InputStreamReader(
               clientSocket.getInputStream())); 

     out.println("Hello World"); 

     out.close(); 
     in.close(); 
     clientSocket.close(); 
    } 
    catch(IOException e) 
    { 
     System.err.println("Error occured " + e); 

    } 
} 
} 

結果豪爾讀取的後續。

Error occured java.net.ConnectException: Connection refused: connect 

這是什麼原因。它只是錯誤的主機地址?

+1

那麼你期望在端口16000上收聽*? – 2012-02-06 11:29:42

+0

首先在同一臺機器上的端口16000上設置服務器套接字,然後運行相同的代碼 – Johnydep 2012-02-06 11:35:37

+0

1)請告訴我們發生錯誤的線路 2)請顯示服務器代碼。 – 2012-02-06 11:36:15

回答

4

從你給你的代碼似乎表明,目前沒有監聽端口16000的套接字連接到。

如果是這樣的包含您需要實現像

ServerSocket serverSocket = null; 
try { 
    serverSocket = new ServerSocket(16000); 
} 
catch (IOException e) { 
    System.err.println("Could not listen on port: 16000."); 
    System.exit(1); 
} 

更多信息可以在the Java online documentation被發現和a full example東西的情況。

2

使用套接字,無論您使用何種語言,您都可以使用socket_connect啓動連接,或者使用socket_listen和socket_accept進行監聽和接受。你的socket_connect調用嘗試連接到一個似乎沒有聽任何東西的IP地址。

+0

恐怕'Socket'構造函數會在這種情況下進行連接。另一方面,需要'ServerSocket',你需要調用'accept()'方法來接收'Socket'端點。 – 2012-02-06 11:35:36

+0

我只是想說明功能。 – 2012-02-06 11:38:06

+0

我剛剛看到你的答案的最後一點(哎呀);)你是對的。 – 2012-02-06 11:47:40