0
public static void waitUntil(String prompt, InputStream instr) {
            while (true) {

                try {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (instr.available() >= 5) {
                        byte[] buff = new byte[1024];
                        int ret_read = 0;
                        ret_read = instr.read(buff);
                        if (ret_read > 0) {
                            if ((new String(buff, 0, ret_read)).contains(prompt)
                                    && flag) {
                                break;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }      

If if remove that thread.sleep(1000) or even i reduce the to less than 1000 its not working properly.

Question : How to read java socket inputstream without thread.sleep() till all all incoming bytes are arrived?

Dyrandz Famador
  • 4,499
  • 5
  • 25
  • 40
Vas
  • 161
  • 1
  • 10

2 Answers2

0
if (instr.available() >= 5) {

Don't do that.

Instead of checking how many bytes are available, just try to read some into a buffer.

That will block until at least one byte is available, and then return as many as there are (that also fit into the buffer).

If that does not return all the bytes you need, loop until you get them.

If you just want to read everything, check out this thread: Convert InputStream to byte array in Java . Personally, I use Commons IO for this.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
0

Use DataInputStream.readFully() with a buffer size of 5 (in this case, or more generally the size of data you're expecting), and get rid of both the sleep and the available() test.

user207421
  • 305,947
  • 44
  • 307
  • 483