异步任务读取阻塞

asynctask read blocking

private byte[] sendCommand (byte[] command){
        try {
            nos.write(command);
            nos.flush();

            byte[] buffer = new byte[4096];
            int read;
            while ((read = nis.read(buffer, 0, 4096)) > 0 && isConnecting) {
                // Read the response
                temp_data = new byte[read];
                System.arraycopy(buffer, 0, temp_data, 0, read);
            }

我在 doInBackground() 中调用了 3 次 sendCommand。 我希望在发送第一个命令后有 13 个字节的响应,然后在我的第二个命令中有一个字节,然后在我的第三个命令中有大约 1kB。

问题 1:第一次调用 sendCommand() 读取 13 个字节作为响应,但由于没有更多数据,读取在 while 条件下阻塞。我怎样才能做到运行而不阻塞?

问题2:是否可以在一个线程中发送重复的写入和读取? 因为对于 sendCommand() 的第二次调用,我得到相同的 13 个字节而不是 1 个字节的响应。我想知道输出流是否没有正确发送命令。

您的读取正在阻塞,因为您要求它检索 4k 字节。虽然它 可能 return 在读取所有请求的字节之前,它会阻止这样做。您应该只尝试读取您期望的字节数:

byte[] response = new byte[expectedLen];
new DataInputStream(nis).readFully(response);
return response;

我不得不摆脱 while 循环,所以我只读了一次。我仍然不明白为什么它不会立即结束 while 循环,但同时删除循环有效。