【问题标题】:How to 'clean' InputStream without closing it?如何在不关闭的情况下“清理” InputStream?
【发布时间】:2016-08-15 17:06:03
【问题描述】:

客户端代码sn-p。基本上它从标准输入中读取数据并将消息发送到服务器。

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();
    }
}

服务器代码 sn-p。从流中打印一条消息。

 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

我面临的问题是,服务器不仅会打印收到的消息,还会打印它之前的所有消息。

问题:如何在不关闭它的情况下重置“干净”InputStream。如果这是不可能的,那么首选的解决方案是什么?

【问题讨论】:

    标签: java sockets inputstream


    【解决方案1】:

    你不需要“清理”流——你只需要在每一行之后重置缓冲区。使用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();
    }
    

    【讨论】:

    • 愚蠢的错误:)。 Tnx
    猜你喜欢
    • 2018-09-14
    • 2016-08-18
    • 1970-01-01
    • 2020-03-09
    • 2014-06-27
    • 1970-01-01
    • 2012-01-01
    • 2010-12-04
    • 2014-07-30
    相关资源
    最近更新 更多