在okhttp中使用http2时,为什么对同一主机的多个请求不只使用一个连接

When using http2 in okhttp, why multi requests to the same host didn't use just one connectoin

我想测试一下okhttp的http2功能。我以异步方式向同一主机发出多个请求。但是,我发现,它涉及多个连接,因为协议是h2,它应该只使用一个连接,对吧? 代码如下。 啊,我用的是okhttp2.5

public class Performance {
    private final OkHttpClient client = new OkHttpClient();
    private final Dispatcher dispatcher = new Dispatcher();
    private final int times = 20;

    public Performance(){
        dispatcher.setMaxRequestsPerHost(2);
        client.setDispatcher(dispatcher);

        // Configure the sslContext
        // MySSLSocketFactory mySSLSocketFactory = new MySSLSocketFactory();
        // client.setSslSocketFactory(mySSLSocketFactory);
        // client.setHostnameVerifier(new HostnameVerifier() {
        //     public boolean verify(String s, SSLSession sslSession) {
        //         return true;
        //     }
        // });
    }
    public void run()throws Exception{
        for(int i=0; i<times; i++) {
            Request request = new Request.Builder()
                .url("https://http2bin.org/delay/1")
                .build();
            client.newCall(request).enqueue(new Callback() {
                public void onFailure(Request request, IOException e) {
                    e.printStackTrace();
                }

                public void onResponse(Response response) throws IOException {
                    System.out.println(response.headers().get("OkHttp-Selected-Protocol"));
                }
            });
        }
    }
    public static void main(String[] args)throws Exception{
        Performance performance = new Performance();
        performance.run();
    }
}

OkHttp 中有 a bug,其中多个并发请求各自创建自己的套接字连接,而不是协调共享连接。这仅在同时创建连接时发生。通过在第二次连接之前产生 500 毫秒来解决。