简体   繁体   中英

Socket reading slow in Android

I am new to Android programming and am writing application that requires use of socket programming. I have written code for socket reading. I am reading around 14 MB of data and following is the code snippet:

dataInputStream = new DataInputStream(client.socket.getInputStream());
int totalRead = 0;
while (totalRead < responseSize) {
       int bytesRead = dataInputStream.read(buffer, totalRead, responseSize - totalRead);

       if (bytesRead < 0) {
         throw new IOException("Data stream ended prematurely");
       }
       totalRead += bytesRead;
}

I have tried running the same code on both JVM and Dalvik (Android device). I'm seeing significant performance differences between these two. In JVM, it's taking around 17 seconds to read the data while it takes more than 40 seconds on Android. Note that I'm using same network for both of these tests.

I am not able to understand these significant performance difference. Initially, I thought this was due to the socket reading code and I tried different methods for reading and still I am getting the same results. view this link for more details . Running code on JVM made it clear that it was not due to socket reading code.

Can you please help me understand why I am seeing this significant performance difference? I'm not sure how to tackle this problem.

Thank you.

You should use a BufferedInputStream to increase the speed of reading. Alternatively you can use the Apache Commons IOUtils read method

Throw this all away and use DataInputStream.readFully(). It already does what you're trying to do, but correctly.

As to why it's slow, it can't go any faster than the writing at the peer.

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