简体   繁体   English

在下面的代码中读取没有thread.sleep()的Java套接字输入流吗?

[英]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. 如果删除该thread.sleep(1000)或什至我将其减少到小于1000,则无法正常工作。

Question : How to read java socket inputstream without thread.sleep() till all all incoming bytes are arrived? 问题 :在没有所有传入字节到达之前,如何在没有thread.sleep()情况下读取java socket inputstream?

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 . 如果您只想阅读所有内容,请查看以下线程: 将InputStream转换为Java中的字节数组 Personally, I use Commons IO for this. 就个人而言,我为此使用Commons IO。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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