# Network Tuning

Weixin Mini Program and MiniGame Network-related APIs are used in the same way, so we use the term "network interface"

# The composition of network interfaces

There are four main types of network interfaces

  • request
  • download
  • upload
  • websocket

# Implementations for different platforms

# Android

  • The request interface uses the underlying components encapsulated in the network-related section of Chromium from version 7.0.10 of the Guest Interface(cronet), previous versions used Http URL Connection system components (system components that depend on system implementations can have platform compatibility issues, we recommend debugging with the new version WeChat)
  • The download interface uses the cronet component from version 7.0.12 of the Guest Terminal, which previously used the Http URL Connection component
  • The upload interface is still using the Http URL Connection component
  • The websocket interface uses the WeChat underlying component wcwss from version 7.0.4 of the Guest Terminal, and has optimized call performance in version 7.0.10

# iOS

  • The request / download interface uses the cronet component from version 8.0.3 of the Guest Terminal. Previous versions used the NS URL Session system component
  • The upload interface is still using the NS URL Session component
  • The websocket interface uses WeChat the underlying component wcwss from version 7.0.20 of the Guest Terminal, prior versions using the SRWebSocket component

# Misunderstood Concepts

# Success / fail / complete callback

  • For the request / download / upload interface, the callback represents the end result of the network request
  • For websocket interfaces, callbacks represent only the result of the interface invocation, and you should listen for its specific events to get the true network connection / request status

# wx.sendSocketMessage/SocketTask.send

In the early days, a single Weixin Mini Program only allowed one WebSocket connection to exist at the same time, so the older version of the base library WebSocket related interfaces were directly designed on wx:

  • wx.connectSocket
  • wx.onSocketOpen
  • wx.sendSocketMessage
  • wx.onSocketMessage
  • wx.closeSocket
  • wx.onSocketClose
  • wx.onSocketError

Now that a single Weixin Mini Program allows multiple WebSocket connections to exist at the same time, the original interface design didn't meet the needs, so the base library added the concept of SocketTask after version 1.7.0 to manage multiple connections through different instances:

  • wx.connectSocket
  • SocketTask.onOpen
  • SocketTask.send
  • SocketTask.onMessage
  • SocketTask.close
  • SocketTask.onClose
  • SocketTask.onError

The original wx.connectSocket interface hosts the creation instance in the new version designnew SocketTaskSo should not use any WebSocket interface that hangs on wx other than wx.connectSocket;After the wx.connectSocket call, listen synchronously to SocketTask.onOpen immediately, otherwise you may miss the onOpen notification

# Performance Analysis

# Android

  • The request / download interface starts with the 7.0.12 version of the Guest Terminal, and the profile information is provided in the callback, which gives the time-consuming information at the key time points during the network connection process, which means as follows
name meaning
redirectStart The time when the first HTTP redirect occurs. Only if there is a jump and the redirect is within the same domain name, otherwise the value is 0
redirectEnd The time at which the last HTTP redirect is completed. Only if there is a jump and it is within the same domain name, otherwise the value is 0
fetchStart The time when the component is ready to grab the resource using an HTTP request, which occurs before checking the local cache
domainLookUpStart The time at which a DNS domain name query begins, equal to the fetchStart value if local caching (i.e. no DNS query) or persistent connection is used
domainLookUpEnd The time when a DNS domain name query completes, equal to the fetchStart value if local caching (i.e. no DNS query) or persistent connection is used
connectStart The time when TCP starts to establish a connection is the same as the fetchStart value if the connection is persistent. Note that if an error occurs at the transport layer and the connection is re-established, the time when the newly established connection is started is shown here
connectEnd Note If an error occurs at the transport layer and the connection is reestablished, the time at which TCP completes the connection (completes the handshake), which is equal to the fetchStart value in the case of a persistent connection. Note that the handshake ends here, including the completion of the secure connection, the completion of the SOCKS authorization, and the completion of the new connection.
SSLconnectionStart Time for SSL to establish a connection, or 0 if it is not a secure connection
SSLconnectionEnd The time at which the SSL establishment completes, or 0 if it is not a secure connection
requestStart The time when an HTTP request begins to read the real document (to finish establishing the connection), including reading from the local cache. When a connection is reconnected by error, the time of the new connection is also shown here
requestEnd The time at which an HTTP request ends reading a real document
responseStart The time at which HTTP begins to receive the response (getting to the first byte), including reading the cache from the local
responseEnd The time when the HTTP response is fully received (up to the last byte), including read from the local cache
rtt Real-time RTT when connecting to the next request
estimate_nettype Evaluated network status unknown, offline, slow 2g, 2g, 3g, 4g, last / 0, 1, 2, 3, 4, 5, 6
httpRttEstimate Protocol layer evaluates the RTT of the current network based on multiple requests (FYI)
transportRttEstimate RTT of the current network assessed by the transport layer against multiple requests (FYI)
downstreamThroughputKbpsEstimate Evaluate the current network download kbps, according to the recent request rtt, packet back situation, combined with the current network situation, a network evaluation results
throughputKbps The actual download kbps of the current network, according to the actual calculation of a download value of this request, the number of bytes received from the beginning of the request to the end of the request * 8 / Request time
peerIP Target IP of the current request
port Target port of the current request
protocol The protocol used for the current request
socketReused Whether to reuse the connection
sendBytesCount Number of bytes sent
receivedBytedCount Number of bytes received

The entire request link is DNS- > Connect- > SSL- > request- > response;The rtt in the table is the rtt in real time during the connection, updated at each stage, and httpRttEstimate and transportRttEstimate are the combined values calculated in conjunction with the previous request

  • The websocket interface provides profile information in the onOpen callback from version 7.0.12 of the Guest Terminal, which gives time consuming information at key points in the network connection process. The specific meaning is as follows
name meaning
fetchStart The time when the component is ready to establish a request using the SOCKET, which occurs before checking the local cache
domainLookUpStart The time at which a DNS domain name query begins, equal to the fetchStart value if local caching (i.e. no DNS query) or persistent connection is used
domainLookUpEnd The time when a DNS domain name query completes, equal to the fetchStart value if local caching (i.e. no DNS query) or persistent connection is used
connectStart The time at which the connection is started is the same as the fetchStart value if the connection is permanent. Note that if an error occurs at the transport layer and the connection is re-established, the time at when the newly created connection started is shown.
connectEnd The time to complete the connection establishment (complete handshake), if a persistent connection, is equal to the fetchStart value. Note If an error occurs at the transport layer and the connection is reestablished, Note that the handshake ends here, including the completion of the secure connection, the completion of the SOCKS authorization, and the completion of the new connection.
rtt Time consuming for a single connection, including connect, tls
handshakeCost It takes time to shake hands.
cost Time taken from upper layer request to return

The entire request link is DNS- > Connect;In the tableconnectEnd - connectStartrepresents pure TCP connection time,domainEnd - domainStartIt means that domain name resolution takes time; The two steps above plus handshakeCost represents the time spent on a single connection request

# iOS

  • The request / download interface provides profile capabilities from version 8.0.3 of the Client
  • The websocket interface provides profile capability from version 7.0.20 of the Guest Account

# prompt

  • When encountering network problems, in addition to judging whether the network state is connected, you can also analyze the user's current network state through rtt to dynamically adjust the timeout parameters
  • The network request provides the enableProfile parameter, which defaults to true and can be closed by passing in false

# Optimization recommendations

# Switch back and forth in the background

Weixin Mini Program After 5 seconds, the network request will be interrupted, and the developer will receive an interrupted callback.

# Change of state

Wx.onNetworkStatusChange notifies you of a change of state.

# Weak change of state

The base library, starting with version 2.19.0, provides wx.onNetworkWeakChange notification of weak network changes. Many timeout class problems are caused by users being on a weak network. This event can be used to give users better hints

Of the eight most recent network requests, one of the following three phenomena was determined to be weak

  • More than three connection timeouts occur
  • Appear three times RTT over 400
  • More than three bag losses occurred

Weak network incident notification rules are: weak network state change when the immediate notification, the same state within 30 seconds at most notice

# Request / download new protocol

Starting with Android 7.0.12 / iOS 8.0.3, the following three new parameters are available

name meaning
enableHttp2 If background support, try using the Http2 protocol
enableQuic If background support, try using the Quic protocol
enableCache Caching content. Same request reads local content first

H2 connection speed is faster, it is recommended to support, here need to note that the header of h2 is required to be all lowercase, open the enableHttp2 switch need to pay attention to the code logic

# perMessageDeflate

Compression parameters are now fully supported on Android and iOS

# Problem sweep

# Error return rules for different platforms

# Android

Error returns for cronet can refer to: https://chromium.googlesource.com/chromium/src/+/master/net/base/net_error_list.h

WebSocket Interface Common Errors

name meaning
Underlying Transport Error The anomaly is probably caused by no network.
Timer Expired Overtime, weak or no network
The total timed out Overtime, weak or no network
TLS handshake failed TLS negotiation failed
TLS handshake timed Tls negotiation timeout, consider retrying
Invalid HttpCode The server was configured in an error

# iOS

Cronet error returns reference with Android

Upload General return Chinese information plus kcferrordomaincfnetwork can directly search for specific corresponding error messages on the official website of Apple developers to assist in the analysis and resolution

# IPv6 is slow.

Android Http URL Connection is to try each ip address in RFC 3484 order, where it should be v6 first, but when the system tries v6 connection time out, it will try v4 again in order.Although it may eventually be possible to complete within the set timeout of 60s, the overall amount of time becomes longer, with the phenomenon of a very long request time for the request interface. This problem was resolved after the client version 7.0.10 switched to cronet

# Certificate Issues

The annotations of the certificate are documented: https://developers.weixin.qq.com/minigame/dev/guide/base-ability/network.html

  1. Certificates are expired or invalid

Can be verified by https://myssl.com/ssl.html or other online tools, because of the compatibility of Android phones, the verification results are not guaranteed to be valid for all Android machines.

  1. The certificate chain is incomplete

The root certificate for Android is incomplete. If the server is using an intermediate certificate and the corresponding root certificate cannot be found on the Android phone, a related SSL error occurs, and the server needs to configure the full certificate chain.

  1. WSS protocol to port 80 failed

Port 80 corresponds to http default does not do certificate verification, wss should choose port 443

# not in domain url

The requested url is not in the domain name list, there are several possibilities for experiencing this problem

  1. The requested url is not in the mp configured domain name list
  2. The redirect url is not in the domain name list
  3. The port requested by websocket is not configured
  4. The configured domain name is not valid (very low probability)

# network is down

The iOS 14 system adds a local network switch. If it is turned off, the local area network does not work. The system interface says network is down. The system currently does not provide a way to detect the switch. Developers need to prompt users to open permissions based on the error message