2015-07-01 61 views
1

我遇到了一個非常奇怪的問題,這讓我在過去兩天中感到沮喪。我試過在這裏尋找類似的問題,但沒有找到解決辦法。BufferedWriter無法在OS X上刷新套接字的外流

我正在使用套接字從遠程telnet會話記錄器讀取到Java文件。
我爲輸入和輸出流定義了一個BufferedWriter和Reader,並將每個readLine刷新到一個文件中。在登錄時,我得到一個特定的字符串,使用outputStream插入一個密碼,並開始在一個循環中讀取instream。這在Windows上完美運行,沒有任何問題。

現在,我試着在Mac OS X(Yosemite)上運行相同的代碼。我得到第一行(要求我插入密碼),通過調試我已經注意到我也在向BufferedWriter寫入密碼。但是,出於一些奇怪的原因,在下一次readLine迭代中,代碼不會獲得日誌輸出,而是停滯在下一個readLine實例上。如果它是空的,它應該退出循環。我已經在Mac上手動檢查(使用secureCRT)打開Telnet會話,並使用密碼運行O.K。在插入一個錯誤的密碼時,我也應該得到一行(「密碼不正確)」,但是在下一個readLine上,我什麼也沒得到,它只是卡住了。在這裏做錯了嗎?它應該在MAC上有不同的效果嗎?它真的能讓我在這裏節省。謝謝!

這個片段是線程的一部分,但它與問題無關(或者所以我認爲),實際文件本身的線程之外創建的。

public void run(){ 
    String line = "-1"; 

    try { 
     socket = new Socket(JSONReader.getPropertyByName("files/properties.json", "LOGGER_DNS_NAME"), 5550); 
    } catch (IOException e1) {   
     e1.printStackTrace(); 
    } 

    try {    
     bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
     instream = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     while ((line = instream.readLine()) != null) {   

      // Insert Username and Password in the Telnet session  
      line = instream.readLine(); 

      if(line.startsWith("Please")){     
       bw.write("password"); 
       bw.newLine(); 
       bw.flush();    
      }   

      if (line.startsWith("Press")) { 
       System.out.println("Reached log"); 
       bw.write("d"); 
       bw.newLine(); 
       bw.flush(); 
      } 

      if (Thread.interrupted()){ 
       try { 
        instream.close(); 
        bw.close(); 
        socket.close(); 
        return; 
       } catch (IOException e) { 
        e.printStackTrace(); 
        System.out.println("Could not close socket"); 
        System.exit(-1); 
       }   
      }   
     } 

     // Write the output to the log file   
     logfile.println(line); 
     logfile.flush(); 
    } catch (UnknownHostException e) { 
     System.out.println("Could not open Telnet session to the server"); 
     System.exit(1); 
    } catch (IOException e) { 
     System.out.println("There was a problem with file creation, or I/O exception"); 
     System.exit(1); 
    } 
} 
+0

你不使用Java 7+嗎? – fge

+0

與你的問題沒有關係,但你應該使用'if(isInterrupted())'而不是'if(Thread.interrupted())'作爲參考,參見[here。]( http://stackoverflow.com/questions/1904072/java-difference-in-usage-between-thread-interrupted-and-thread-isinterrupted) – MalaKa

+0

@fge我正在使用jre 1.8 - 它是否有所作爲? –

回答

1

所以最後,在這兩種情況下嗅探服務器的TCP會話之後,我發現我的問題。

問題是,使用寫入方法時,BufferedWriter會自動生成行結束符(\ n)。除此之外,在基於Linux的Mac OS上,行結尾應該是(\ r \ n)。

所以,而是採用了 「寫」 的方法, 「新線」,我只是用 「追加」,而不是(追加(「密碼\ r \ n))的插入\ r \ n字符串。