2016-08-15 60 views
0

客戶端代碼片段。基本上它從標準輸入中讀取消息並將消息發送到服務器。如何清理InputStream而不關閉它?

public static void main(String[] args) { 

    try (Socket socket = new Socket("localhost", 1200)) { 
     OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.US_ASCII); 

     Scanner scanner = new Scanner(System.in); 
     for (String msg = scanner.nextLine(); !msg.equals("end"); msg = scanner.nextLine()) { 
      writer.write(msg + "\n"); 
      writer.flush(); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

Server code snippet。從流中打印消息。從客戶端

public void run() { 

    try (InputStreamReader reader = new InputStreamReader(this.socket.getInputStream(), StandardCharsets 
      .US_ASCII)) { 

     StringBuilder builder = new StringBuilder(); 

     for (int c = reader.read(); c != -1; c = reader.read()) { 

      builder.append((char) c); 
      if ((char) c == '\n') 
       System.out.print(builder); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

輸入:

Text1 
Text2 

服務器輸出:

Text1 
Text1 
Text2 

的問題,我面對的是服務器輸出不剛剛收到的消息,而且之前的所有消息。

問題:如何在不關閉的情況下重置'clean'InputStream。如果這是不可能的,什麼是首選的解決方案?

回答

2

你不需要'清理'流 - 你只需要在每一行之後重置緩衝區。試着像使用StringBuilder.setLength如下:

if (c == '\n') { 
    System.out.print(builder.toString()); 
    builder.setLength(0); 
} 

在另一方面,我強烈鼓勵手動念臺詞像。考慮像在客戶端代碼中那樣使用Scanner,或者使用BufferedReader

try (final BufferedReader reader 
     = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII))) { 
    for (String line = reader.readLine(); line != null; line = reader.readLine()) { 
    System.out.println(line); 
    } 
} catch (final IOException ex) { 
    ex.printStackTrace(); 
} 
+0

愚蠢的錯誤:)。 TNX –