2013-04-24 33 views
0

當我構建一個客戶端 - 服務器聊天程序時,我遇到了一個非常奇怪的問題(因爲它總是在以前工作)。服務器接受套接字,但之後套接字不能接收任何東西

serversocket毫無問題地接受客戶端的傳入連接,但是當我試圖從套接字的輸入流讀取時,整個方法阻塞並且只有在關閉客戶端套接字時纔會釋放。

我甚至用docs.oracle.com上的示例代碼嘗試過它,但問題依然存在。

任何人都可以指出我顯然沒有看到的錯誤嗎?

服務器代碼:

public class Server { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) throws IOException { 
    System.out.println("Creating server socket"); 

    ServerSocket internetSocket = new ServerSocket(60000); 
    if(!internetSocket.isClosed()) { 

     while(true) { 
      Socket s = internetSocket.accept(); 
      System.out.println("accepted socket!"); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream())); 

      String line = null; 
      while((line = reader.readLine()) != null) { 
       System.out.println(line); 
      } 
     } 
    } 
} 
} 

客戶機代碼:

public class Client { 

public static void main(String[] args) throws IOException { 
    Socket s = null; 
    try { 
     s = new Socket("localhost", 60000); 
    } catch (UnknownHostException ex) { 
     Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    PrintWriter outStream = new PrintWriter(s.getOutputStream()); 
    for(int i=0; i<10; i++) { 
     outStream.println("test"); 
     System.out.println("Sending the message \"test\""); 

     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    s.close(); 
} 
} 

回答

2

創建PrintWriter的時候你忘了添加一個真正的第二個參數輸出流printwriter

new PrintWriter(s.getOutputStream(), true); 

這將使它自動刷新。

+0

對不起,但我不能接受這兩個答案;-)我剛剛在PrintWriter中看到了額外的構造函數參數。我想我的代碼寫得太快了。 Anywayz也感謝你指出它! – Tom 2013-04-24 20:29:38

0

方法readLine()等待\ n字符出現在流(該方法將阻塞,直到它看到端線定界符)英寸

嘗試從客戶端發送"test\\n",看看會發生什麼。

還有要記得flush()在客戶端

+0

感謝您的快速響應,但沒有什麼不同。 – Tom 2013-04-24 20:20:02

+0

並確保你flush()的東西到outputStream – WeMakeSoftware 2013-04-24 20:21:50

+0

AHA!以某種方式添加flush()做了詭計!任何想法爲什麼它不會自動刷新?我猜測printwriter初始化? – Tom 2013-04-24 20:25:24