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
。如果這是不可能的,什麼是首選的解決方案?
愚蠢的錯誤:)。 TNX –