Disable Nagle’s Algorithm with OkHttp or Scarlet

Android 客户端使用 OKHTTP 的时候,需要通过修改底层的 Socket 来解决问题,比如设置 TCP 的心跳、修改TCP 的滑动窗口算法等。

相关的代码参考如下:

TCP includes a feature called Nagle’s Algorithm that will postpone sending small messages, in hopes of combining them with future messages. This can save bandwidth, because TCP has to include additional information along with each segment. Combining multiple small messages into a single segment reduces the overall bandwidth used. However, this increases the time it will take for some small messages to be received.

If you want all of your messages to be sent with the lowest latency possible, and you are willing to use additional bandwidth, you should disable Nagle’s Algorithm. WebSocket connections made with OkHttp have Nagle’s Algorithm enabled by default. There was an issue about this back in 2013, and the fix was to add the socketFactory and sslSocketFactory options.

To disable Nagle’s Algorithm using these options, you have to create classes that extend SocketFactory and SSLSocketFactory and call setTcpNoDelay(true) on their underlying sockets. You can use the following classes I created, which use composition:

SocketFactory

SSLSocketFactory

Putting It Together

You can create an OkHttpClient that uses these classes as follows:

WebSocket connections that your OkHttpClient makes will have Nagle’s Algorithm disabled.

Scarlet

Scarlet is a library from Tinder that uses OkHttp for WebSocket connections. If you pass the OkHttpClient that you created above to OkHttpClientUtils#newWebSocketFactory, all WebSocket connections made with Scarlet will have Nagle’s Algorithm disabled.

Note that all Scarlet WebSocket connections use OkHttp. As of writing this post, Scarlet is still using OkHttp version 3.11. OkHttp 4 has been out for over a year. If you are starting a new project, consider using OkHttp directly, rather than using Scarlet.

参考链接


Disable Nagle’s Algorithm with OkHttp or Scarlet

发布者

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

发表评论前,请滑动滚动条解锁
三十岁