2014-06-20 75 views
1

我有客戶端和服務器的服務器站點。服務器運行良好,但客戶端網站,當我試圖閱讀不是。從套接字讀取後無法寫入

但是,當我刪除此代碼,它的工作原理:

while((read = br.readLine()) != null){ 
    System.out.println("in reading"); 
    finale += read; 
    output.setText(finale); 
}   
br.close(); 

下面是完整的代碼:

try{ 
    Socket connection = new Socket("localhost",PORT); 
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream())); 
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    pw.println("hi connection estabilished"); 
    pw.flush(); 
    String str,read = "",finale = ""; 
    while(connection.isConnected()){ 
     System.out.println("start"); 
     if(zapis == true){ 
      str = input.getText(); 
      pw.println(str); 
      pw.flush(); 
      input.setText(""); 
      zapis = false; 
     } 
     System.out.println("top of the reading"); 
     while((read = br.readLine()) != null){ 
      System.out.println("in reading"); 
      finale += read; 
      output.setText(finale); 
     }   
     br.close(); 
    } 
} catch(IOException e) { 
    System.out.println("error " + e); 
} 

這是一邊收聽我的按鈕的動作剛下課

class Listener implements ActionListener{ 

@Override 
public void actionPerformed(ActionEvent e) { 
    Main.zapis = true; 
} 
} 
+0

你可以試試這個PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true); – ppuskar

+0

仍然無效 –

+0

你是什麼意思「它不工作」?有什麼異常? –

回答

0

顯然,你在循環while(connection.isConnected()){之外打開br,但是y你可以在循環中關閉它。

你應該嘗試寫你的最後一塊(就是那個讓當你刪除它的工作原理)爲:與循環結束

System.out.println("top of the reading"); 
    while((read = br.readLine()) != null){ 
     System.out.println("in reading"); 
     finale += read; 
     output.setText(finale); 
    }   
} 
br.close();