2012-03-03 102 views
1

我在這裏介紹了客戶端和服務器端程序。客戶端通過發送字符串與服務器通信,服務器然後將字符串轉換爲大寫字母併發回。問題是客戶端沒有收到來自服務器的任何字符串。只有服務器打印2個字符串,然後服務器拋出IOException。我想這是因爲客戶端關閉了連接。但爲什麼客戶端沒有收到來自服務器的任何消息?如何解決這個問題? 感謝客戶端和服務器之間的通信出現了一些故障

Client: 
package solutions; 

import java.io.*; 
import java.net.*; 

class SocketExampleClient { 

    public static void main(String [] args) throws Exception { 

    String host = "localhost"; // hostname of server 
    int port = 5678;   // port of server 
    Socket s = new Socket(host, port); 
    DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 
    DataInputStream dis = new DataInputStream(s.getInputStream()); 

    dos.writeUTF("Hello World!"); 
    System.out.println(dis.readUTF()); 

    dos.writeUTF("Happy new year!"); 
    System.out.println(dis.readUTF()); 

    dos.writeUTF("What's the problem?!"); 
    System.out.println(dis.readUTF()); 

    } 
} 

服務器:

package solutions; 

import java.io.*; 
import java.net.*; 

class SocketExampleServer { 

    public static void main(String [] args) throws Exception { 

    int port = 5678; 
    ServerSocket ss = new ServerSocket(port); 
    System.out.println("Waiting incoming connection..."); 

    Socket s = ss.accept(); 
    DataInputStream dis = new DataInputStream(s.getInputStream()); 
    DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 

    String x = null; 

    try { 
     while ((x = dis.readUTF()) != null) { 

     System.out.println(x); 

     dos.writeUTF(x.toUpperCase()); 
     } 
    } 
    catch(IOException e) { 
     System.err.println("Client closed its connection."); 
    } 
    } 
} 

輸出:

Waiting incoming connection... 
Hello World! 
Happy new year! 
What's the problem?! 
Client closed its connection. 

回答

2

你的主程序退出它有機會從服務器讀取響應之前運行一個單獨的線程。如果你添加下面的代碼,它會正常工作。 :)更新 - 我剛剛意識到你的代碼在我的電腦上工作正常 - 並且它按照預期輸出字符串。 DataInputStream.readUTF()正確阻塞並接收響應。你仍然有問題嗎?

Thread t = new Thread(){ 
public void run() 
{ 
    for(;;) 
    { 
     String s = null; 
    try 
     { 
     s = dis.readUTF(); 
    } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 
     while(s!=null) 
     { 
      System.out.println("Output: " + s); 
     try 
     { 
     s = dis.readUTF(); 
    } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
    } 
    }}}}; 
    t.start(); 
+0

但是爲什麼在讀取服務器響應之前退出?客戶端寫入然後讀取,然後寫入 - 讀取等等。它是按順序的。 – uml 2012-03-03 14:29:38

+0

它以大寫字母打印服務器的響應。儘管在服務器端,客戶端傳入的字符串不會被打印在屏幕上。 – uml 2012-03-03 17:20:19

0

凡在您的客戶端的代碼,你等待服務器的輸入?當你的客戶完成發送它終止的消息並且套接字關閉時,

你應該聽到服務器的解答或look at this example

+0

客戶端發送字符串下面的下一行應該從服務器讀取字符串。 – uml 2012-03-03 13:55:45

+0

哦對不起,我只是不習慣看到它這樣。我明白你試着做一些非常快的事情來檢查它,但你應該使用上面例子中描述的方法。 – giorashc 2012-03-03 15:52:50