Java socket BufferedReader 一次从循环中读取所有输入

Java socket BufferedReader reads all inputs from loop at once

我有一个简单的服务器-客户端应用程序。有一个选项,客户端可以将其发送到服务器,以读取生成的数据。

void getManyFromServer(int numberOfGets){
    try{
            for(int i=0;i<numberOfGets;i++){

                    fromServer = sockIn.readLine();
                    fromServer+="\n";
                    textArea.append(fromServer);
            }
        } catch(IOException exc){
            /*...*/
    }
}

如你所见,我想读取数据 10 次,因为服务器每 3 秒会生成 10 个不同的数字:

Random randomGenerator = new Random();
        double MEAN = 4.0f; 
        double VARIANCE = 0.01f;

    for(int i=0;i<10;i++){
        out.println(Double.toString(MEAN + randomGenerator.nextGaussian()* VARIANCE));
        try{
            Thread.sleep(3000);
        } catch(InterruptedException e){
            /*...*/
        }

问题是 - 客户端等待所有 "out.println" 完成,然后立即在 textArea 中打印所有内容。

如何模拟将数据写入 textArea 之间的 3 秒延迟?

从客户端打印出 println,您可能会发现它并没有一次读取所有内容。相反,您可能会通过在 Swing 事件线程上执行此读取操作来冻结您的 GUI,从而阻止它向文本组件写入文本。解决方案:使用后台线程(例如 SwingWorker)进行读取。请阅读 Lesson: Concurrency in Swing 了解更多信息。

例如,

private void getManyFromServer2(final int numberOfGets) {
  new SwingWorker<Void, String>() {
     @Override
     protected Void doInBackground() throws Exception {
        try {
           for (int i = 0; i < numberOfGets; i++) {

              fromServer = sockIn.readLine();
              fromServer += "\n";
              // textArea.append(fromServer);
              publish(fromServer);
           }
        } catch (IOException exc) {
           exc.printStackTrace();
        }
        return null;
     }

     @Override
     protected void process(List<String> chunks) {
        for (String line : chunks) {
           textArea.append(line);
        }
     }

     @Override
     protected void done() {
        try {
           get();
        } catch (InterruptedException | ExecutionException e) {
           e.printStackTrace();
        }
     }
  }.execute();
}