1

I have simple server-client application. There is an option, which client can send to the server, to read generated data.

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

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

As you can see, I want to read data 10 times, because server will generate 10 different numbers, every 3s:

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){
            /*...*/
        }

The problem is - clients waits until all "out.println" are finished and then prints everything at once in textArea.

How can I simulate 3s delay between writing data into textArea?

1 Answer 1

4

Print out a println from the client, and you'll likely see that it's not reading everything in all at once. Instead, you're likely freezing your GUI by doing this reading on the Swing event thread, and thus preventing it from writing the text to the text component. Solution: use a background thread such as a SwingWorker to do the reading. Please read Lesson: Concurrency in Swing for more on this.

e.g.,

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.