Search code examples
androidokhttphttp2

using http2 with okhttp in android, why 20 stream is created for 20 request


Using okhttp 3.8.1

I use okhttp http2 to request for 20 same pictures at the same time using multiple thread with same okhttpclient.

I use tcp dump to capture the traffic. Found that there are still 20 tcp stream, with one much larger, and the other 19 smaller.

My question is what are these 19 streams for. Or am I using ok http in the wrong way?

    up      down    count 
    2510    56320   1
    352     3492    19

my code is something like this

    OkHttpClient client = builder.build();
    for (int i = 0; i < urls.length; i++) {
        runTest(urls[i], client);
        }
...
    private void runTest(...)
        new Thread(new Runnable() {
                @Override
                public void run() {
                        Request request = new Request.Builder()
                                .url(url)
                                .build();
                        try {
                            Response response = client.newCall(request).execute();
                            result = response.body().string();
                        } catch (IOException e) {
                        }
                    }
                }
            }).start();
    }

Solution

  • the answer lies in the discussions here https://github.com/square/okhttp/issues/3442

    in brief, when the concurrent requests starts, there's not a usable tcp channel yet, so okhttp create new tcp channel for each request(20). after the first one is establish, with the coalescing mechanism, the other requests will abandon the tcp channel it create and use the first established one.