2011-05-18 74 views
0

我想在這裏做一個編程練習,使客戶端和服務器與套接字一起工作。對於他們之間的通信,我使用PrintWriter和InputReader.What即插即用:如何檢查是否服務器正在嘗試向客戶端發送什麼,而客戶端正在等待輸入?在這一點上,客戶端循環是這樣的:輸入問題Java插座

do { 
       outToServer.println(inFromUser.readLine()); 
       String fromServer=inFromServer.readLine(); 
       if(fromServer.equals("OK")){ 
        clientSocket.close(); 
       }else{ 
        System.out.println(fromServer); 
       } 
      } while (!clientSocket.isClosed()); 

的問題是,在某些情況下,服務器需要打印多行,之前需要輸入again.Instead它打印,然後1號線生病需要輸入的東西,然後另一條線來等。有沒有辦法解決這個問題?謝謝 。

+0

你想創建什麼?你的目標是製作一個聊天應用程序嗎? – doNotCheckMyBlog 2011-05-18 17:50:02

+0

沒有它只是一個簡單的練習是你發送命令到服務器,它做的事情。 – Giannis 2011-05-18 20:01:46

回答

0

所以你將需要封裝

outToServer.readLine(); 

在while循環,有一個布爾條件類似於hasNext()函數。您可能需要將其設置如下:

String x = outToServer.readLine(); 
//while x doesn't equal whatever readLine would return if there's nothing to read 
//I'm not sure if this is a null String or not 
while(x!=null){ 
    System.out.print(x);//print it however you wish 
    String x = outToServer.readLine(); 
} 

,然後根據需要做類似的事情了inFromServer。

+0

讓我知道這是否有幫助。 – Vinay 2011-05-18 18:11:09

+0

如果您使用的是BufferedReader,則流的結尾會返回空字符串,因此上述條件應該是正確的。 http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine() – Vinay 2011-05-18 18:15:51

+0

感謝現在不好測試。 – Giannis 2011-05-18 20:01:18