简体   繁体   中英

Read Java socket inputstream without thread.sleep() in the below code?

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?

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.

使用DataInputStream.readFully()的缓冲区大小为5(在这种情况下,或更通常是您期望的数据大小),并摆脱sleep和available()测试。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM