Search code examples
javamultithreadingsocketsandroid-asynctasksingle-threaded

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);
            }

I call sendCommand three times in my doInBackground(). I expect 13 bytes of response in after sending a first command, then one byte in my second one then about 1kB in my third one.

Question 1: The first call to sendCommand() reads 13 bytes in response but the read blocks in the while condition because there is no more data. How can I make it run without blocking?

Question 2: Is it possible to send repeated write and reads in one thread? Because for the second call to sendCommand(), I get the same 13 byte not 1 byte of response. I wonder if the outputstream is not sending the command properly.


Solution

  • I had to get rid of the while loop so I read only once. I still don't understand why it would not end the while loop immediately but removing the loop works for the mean time.