swing - Java socket BufferedReader reads all inputs from loop at once -


i have simple server-client application. there option, client can send server, 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 can see, want read data 10 times, because server 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 - clients waits until "out.println" finished , prints @ once in textarea.

how can simulate 3s delay between writing data textarea?

print out println client, , you'll see it's not reading in @ once. instead, you're freezing gui doing reading on swing event thread, , preventing writing text text component. solution: use background thread such swingworker reading. please read lesson: concurrency in swing more on this.

e.g.,

private void getmanyfromserver2(final int numberofgets) {   new swingworker<void, string>() {      @override      protected void doinbackground() throws exception {         try {            (int = 0; < 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) {         (string line : chunks) {            textarea.append(line);         }      }       @override      protected void done() {         try {            get();         } catch (interruptedexception | executionexception e) {            e.printstacktrace();         }      }   }.execute(); } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -