Http://medium.com/cchiappini…

The author is medium.com/cchiappini

Published: August 22, 2016 -5 minutes to read

Cronet is a web library for Android and iOS applications. Cronet is the Chromium network stack packaged as a library: that means Chrome uses the stack every day.

Cronet can improve application network performance by reducing latency and increasing throughput.

This paper introduces Cronet library and its usage. You can find an example of how to use Cronet here. This example shows how Cronet can be used to load a bunch of images stored on Google Cloud.

Today’s Network

It seems like everyone is using some variation of OkHttp. You can use OkHttp directly from the Android framework, or Volley (configured to use the framework or OkHttp).

The framework version of the API, HttpUrlConnection, provides a synchronization API that runs on a single thread.

OkHttp provides asynchronous apis, streams, and HTTP/2.

Volley provides request priority, multi-concurrent network requests, and request cancellation. Volley keeps the response in memory during parsing, so it is more powerful for small HTTP requests.

The Cronet API allows asynchronous requests.

Chromium network stack

The Chromium Web protocol stack offers several advantages to improve page load times.

Every time a host establishes a connection, various activities, such as DNS resolution and handshakes, take place. The Chromium protocol stack uses the Socket Late Binding mechanism to solve this problem.

Modern pages require a lot of resources, and resource priorities are a challenge for browsers. The Chromium protocol stack uses resource prioritization, and all requests are sent to the server as a priority marker, allowing the server to respond in the appropriate priority order.

Chromium also provides a disk cache to cache network resources.

Other Cronet functions

Cronet uses JAVA NIO ByteBuffers when reading and writing data, providing better performance for I/O functionality.

As the Chromium network stack, Cronet also allows you to set the priority of requests. See the code example in the Priority section.

Supports HTTP/2 and QUIC

One of the advantages of using Cronet is support for HTTP/2 and QUIC. If you are familiar with both protocols, feel free to skip the sections below and go to how to use them.

HTTP/2

HTTP/2 addresses many of the current shortcomings of HTTP by evolving standards. In contrast to its predecessor, HTTP/2.

  • It’s binary, not textual
  • Is fully multiplexed, rather than ordered and blocked: this allows parallel requests to be made using a single connection
  • Use header compression to reduce overhead
  • Allows the server to actively “push” the response into the client cache.

QUIC

The QUIC protocol (Quick UDP Internet Connections) was announced by Google in 2012 to replace HTTP/2 with UDP instead of TCP.

QUIC allows connections to be created with lower latency and is a multiplexing protocol with no head blocking. This means that it solves the problem of packet loss and blocks only individual data streams, rather than all of them.

All major Google sites on the desktop and Android Chrome, as well as many Android applications, use QUIC.

The performance test reported that web pages loaded 5% faster and web searches were 99% faster by a second. YouTube, one of the places that uses QUIC, reports improving the quality of the experience by reducing the amount of stress (video pauses) by 30 percent.

usage

CronetEngine

The first step is to instantiate a CronetEngine, which you can find in viewAdapter.java. Normally, you only need one instance of CronetEngine, so in the example, it is a static variable created by the method getCronetEngine(Context Context).

There are various configuration options available through CronetEngine.Builder when CronetEngine is created.

  1. Control cache (select one)
  • By using a 100KB memory cache.
engineBuilder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_IN_MEMORY, 100 * 1024)
Copy the code

Or by using a 1MB disk cache.

engineBuilder.setStoragePath(storagePathString);
engineBuilder.enableHttpCache(CronetEngine.Builder.HttpCache.DISK,
 1024 * 1024);
Copy the code
  1. Use the following methods to enable HTTP2
 engineBuilder.enableHttp2(true)
Copy the code
  1. Use the following methods to enable QUIC
engineBuilder.enableQuic(true)
Copy the code
  1. If you know that the server is using QUIC, you can use the
engineBuilder.addQuicHint(...)
Copy the code

In fact, Cronet didn’t know the server was saying QUIC until it received the first response and didn’t try to use it at first. Using addQuicHint (…). Method, there is no need to find out whether the server supports QUIC. Also, by using

cronetBuilder.setStoragePath(...)
cronetBuilder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK_NO_HTTP, 1024 * 1024)
Copy the code

This information is persisted in different sessions and used from the first request. Using disk caching also persists the encrypted information of the server. For the establishment of a QUIC 0-RTT session, 0-RTT actually uses the QUIC server information from the previously negotiated session.

UrlRequest

On Android, Cronet provides its own Java asynchronous API. As you can see from the ViewAdapter class, you first need to extend urlRequest.callback to handle events during the request life cycle.

You have four different callback methods that are invoked by the actor once the request is fully and partially completed.

onRedirectReceived(...)
onResponseStarted(...)
onReadCompleted(...)
onSucceeded(...)
Copy the code

Once you implement the request callback, you can make the request by using the UrlRequestBuilder, which combines the URL, callback, executor, and Cronet engine.

// Create an executor to execute the request
Executor executor = Executors.newSingleThreadExecutor();
UrlRequest.Callback callback = new SimpleUrlRequestCallback(holder.imageViewCronet);
UrlRequest.Builder builder = new UrlRequest
.Builder(ImageRepository.getImage(position), callback, executor, cronetEngine);
// Start the request
builder.build().start();
Copy the code

priority

A request can have five types of priority.

  • REQUEST_PRIORITY_IDLE.
  • REQUEST_PRIORITY_LOWEST(lowest level)
  • REQUEST_PRIORITY_LOW(Low priority)
  • REQUEST_PRIORITY_MEDIUM(Priority)
  • REQUEST_PRIORITY_HIGHEST(highest priority)

You can set the priority of a Request by using the Builder’s setPriority method.

builder.setPriority(UrlRequest.Builder.REQUEST_PRIORITY_HIGHEST);
Copy the code

HTTPURLConnection

If you rely on java.net.HttpURLConnection API, you can through the use of the Cronet implementation.

HttpURLConnection connection = (HttpURLConnection)engine.openConnection(url);
URL.setURLStreamHandlerFactory(engine.createURLStreamHandlerFactory());
Copy the code

Note that Cronet’s HttpURLConnection implementation has some system implementation limitations. For example, it does not use the system’s default HTTP cache. Considering converting async non-blocking apis to synchronous blocking apis, the Async API may perform better than HttpURLConnection.

debugging

You can use NetLog to get more information about how Cronet handles network requests. To do this, you need to by calling CronetEngine. StartNetLogToFile and CronetEngine stopNetLog to test the code to start and stop the NetLog. Take a look at the method called startNetLog() in the example..netlog () is a good example.

Log files can be read by using the Chrome browser to navigate to Chrome ://net-internals#import.

This is what NetLog looks like.

Note that enabling NetLog tracing affects network performance.

database

As described on the README file, getting the latest version of the library today is a manual process. Depending on the architecture, libraries are between 3 and 5MB in size.

conclusion

Cronet is an open source library that makes HTTP, HTTP/2, and QUIC calls on Android and IOS. Try it on your application today to improve your application’s network performance.

source

www.chromium.org/developers/…

www.chromium.org/developers/…


Translation via www.DeepL.com/Translator (free version)