# Network tuning

Small programs and small games network related API Used in the same way, So we use the term network interface

# Composition of Network Interface

The network interface consists of four main types

  • request
  • download
  • upload
  • WebSocket

# Implementation of different platforms

# Android

  • request Interface from the client 7.0.10 Version Start using Chromium The underlying components encapsulated by the relevant parts of the internal network (Cronet ), Previous versions use HttpURLConnection System components (System components depend on the system implementation will have platform compatibility issues, We recommend to use the new version of WeChat for debugging)
  • download Interface from the client 7.0.12 Version Start using Cronet Components, Previous versions use HttpURLConnection assembly
  • upload Interface is still in use HttpURLConnection assembly
  • WebSocket Interface from the client 7.0.4 Version Start using WeChat's underlying components wcwss, And in the 7.0.10 Version optimizes call performance

# iOS

  • request/download Interface from the client 8.0.3 Version Start using Cronet Components, Previous versions use NSURLSession System components
  • upload Interface is still in use NSURLSession assembly
  • WebSocket Interface from the client 7.0.20 Version Start using WeChat's underlying components wcwss, Previous versions use SRWebSocket assembly

# Misconception

# success/fail/complete Callback

  • for request/download/upload Interface, A callback represents the final result of a network request
  • for WebSocket Interface, A callback represents only the result of an interface call, We should listen to its specific events to get the real network connection./Request status

# wx.sendSocketMessage/SocketTask.send

In the early days, only one Mini Program was allowed to exist simultaneously. WebSocket Connection, So the old base library WebSocket The relevant interfaces are designed directly in the wx Up:

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

Now a single Mini Program allows for the simultaneous existence of multiple WebSocket Connection, The original interface design can not meet the needs, So the base library is in 1.7.0 Added later version. SocketTask The concept, Manage multiple connections through different instances:

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

Original wx.connectSocket Interface hosts the creation instance in the new version design new SocketTask The use, So in addition to wx.connectSocket Outside, Shouldn't beUse any other hanging wx On WebSocket interface in wx.connectSocket After the call, Please synchronize monitoring immediately SocketTask.onOpen, Or you might miss onOpen notice

# Performance analysis

# Android

  • request/download Interface from the client 7.0.12 The version begins, Provided in the callback profile Information, The time consuming information of the key time points in the network connection process is given. The specific meaning is as follows
name meaning
redirectStart The first HTTP The time when the redirect occurred. If there is a jump and it is a redirect within the same domain name, Otherwise the value is 0
redirectEnd The last one HTTP The time when the redirect is complete. There is a jump and redirect within the same domain name only counts, Otherwise the value is 0
fetchStart Components are ready to use HTTP Time to request resources, This happens before checking the local cache
DomainLookUpStart DNS The time the domain name search begins, If a local cache is used (That is nothing DNS query) Or persistent connections, And fetchStart Equal value
domainLookUpEnd DNS Time to complete the domain name search, If a local cache is used (That is nothing DNS query) Or persistent connections, And fetchStart Equal value
connectStart TCP Time to start connecting, If it is a persistent connection, And fetchStart The value is equal. Note If an error occurs at the transport layer and the connection is reestablished, This shows the time when the newly established connection began
connectEnd TCP Time to complete connection establishment (Complete handshake), If it is a persistent connection, And fetchStart The value is equal. Note If an error occurs at the transport layer and the connection is reestablished, This shows when the newly established connection was completed. Notice that the handshake ends here, Including secure connection establishment completed, SOCKS Authorized to pass
SSLconnectionStart SSL Time to connect, If it is not a secure connection, The value is 0
SSLconnectionEnd SSL The time of completion, If it is not a secure connection, The value is 0
requestStart HTTP The time the request to read the real document started (Complete Establish Connection), Includes reading from local cache. Connection error When reconnected, This shows the time of the new connection.
requestEnd HTTP The time the request to read the real document ended
responseStart HTTP Time to start receiving a response (Get to the first byte), Includes reading the cache from the local
responseEnd HTTP Response Time to Complete Reception (Get to the last byte), Includes reading the cache from the local
rtt When the request is connected in real time rtt
estimate_nettype Network Status Evaluated unknown, offline, slow 2g, 2g, 3g, 4g, last/0, 1, 2, 3, 4, 5, 6
httpRttEstimate The protocol layer evaluates the current network's rtt (for reference only)
transportRttEstimate Of the current network evaluated by the transport layer based on a plurality of requests rtt (for reference only)
downstreamThroughputKbpsEstimate Evaluate the kbps of the current network download, According to the rtt of several recent requests, Return the package, With the current network, Results of a network evaluation conducted by
throughputKbps Actual downloaded kbps of the current network, A download value actually calculated from this request, From the start request to Request to close the receipt of byte count * 8/Request time
peerIP Target IP of the current request
port The destination port for the current request
protocol The protocol used for the current request
socketReused Whether to reuse the connection
sendBytesCount Number of bytes sent
receivedBytedCount Bytes received

The entire request link is DNS -> Connect -> SSL -> request -> response In the table rtt In real time during the connection. rtt, Each phase is updated, and httpRttEstimate and transportRttEstimate Is a composite value calculated with the preceding request

  • WebSocket Interface from the client 7.0.12 The version begins, in onOpen Provided in the callback profile Information, The time consuming information of the key time points in the network connection process is given. The specific meaning is as follows
name meaning
fetchStart Components are ready to use SOCKET The time of the request, This happens before checking the local cache
DomainLookUpStart DNS The time the domain name search begins, If a local cache is used (That is nothing DNS query) Or persistent connections, And fetchStart Equal value
domainLookUpEnd DNS Time to complete the domain name search, If a local cache is used (That is nothing DNS query) Or persistent connections, And fetchStart Equal value
connectStart Time to start connecting, If it is a persistent connection, And fetchStart The value is equal. Note If an error occurs at the transport layer and the connection is reestablished, This shows the time when the newly established connection began
connectEnd Time to complete connection establishment (Complete handshake), If it is a persistent connection, And fetchStart The value is equal. Note If an error occurs at the transport layer and the connection is reestablished, This shows when the newly established connection was completed. Notice that the handshake ends here, Including secure connection establishment completed, SOCKS Authorized to pass
rtt The time of a single connection, Include connect, tls
Handshakecost Handshake time consuming
cost Time taken from request to return

The entire request link is DNS -> Connect In the table connectEnd - connectStart On behalf of pure tcp Connection time consuming, domainEnd - domainStart Domain Name Resolution The above two steps are time consuming plus Handshakecost Represents the time taken for a single connection request

# iOS

  • request/download Interface from the client 8.0.3 Version begins to be available profile ability
  • WebSocket Interface from the client 7.0.20 Version begins to be available profile ability

# prompt

  • When it comes to network problems, In addition to determining whether the network state is connected, Can also be accessed by rtt To analyze the user's current network situation, To dynamically adjust timeout parameters
  • Network Request to Provide enableProfile Parameters, The default value is true, Can be accessed by passing in false Stop

# Optimization proposal

# Front and back office switch

Small cut background 5s Later, Will interrupt network requests, The developer will receive interrupted The return, Compatible logic is needed at this time.

# Change of state

When you change of state wx.onNetworkStatusChange Notification, Many network problems were caused by the disconnection of the network. Can give the user a better hint through this event

# Weak change of state

The base library from 2.19.0 The version begins, provide wx.onNetworkWeakChange Weak network change notification, Many timeout problems are caused by the user being in a weak network. Can give the user a better hint through this event

In the last eight network requests, A weak network is determined when one of the following three phenomena occurs

  • More than three connection timeouts
  • Appeared three times rtt Exceed 400
  • More than three packet losses

The weak net event notification rules are: Notify the change of state of weak network immediately. When the state is constant 30s Up to one notification per day

# request/download New agreement

from Android 7.0.12 / iOS 8.0.3 Begin, Provide the following three new parameters

name meaning
enableHttp2 If the backend is supported, Try to use the Http2 agreement
enableQuic If the backend is supported, Try to use the Quic agreement
enableCache The content, Same request to read local content first

h2 Faster connections, Recommended support, Attention needs to be paid here h2 of header It needs to be all lowercase, open enableHttp2 Pay attention to the code logic before switching

# perMessageDeflate

Compression parameters are currently in the Android and iOS Total support

# Troubleshooting

# Error return rules for different platforms

# Android

Cronet The error return can refer to: https://chromium.googlesource.com/chromium/src/+/master/net/Base/net_error_list.h

WebSocket Common Interface Errors

name meaning
Underlying Transport Error Unusual, High probability no network caused
Timer Expired Time out, Weak or no net
The total timed out Time out, Weak or no net
TLS handshake failed tls Failure to negotiate
TLS handshake timed tls Negotiation over time, Consider retrying
Invalid HttpCode The server is misconfigured.

# iOS

Cronet The error returns a reference to the same Android

upload General Back Chinese Information Plus kcferrordomaincfnetwork You can search for specific error messages directly on the apple developer website. Assist in analysis and solution

# ipv6 The Slow Problem

Android HttpURLConnection Is in accordance with the RFC 3484 Order to try each ip Address, This is supposed to be v6 Priority, But the system tried v6 The connection timeout will be tried again in order v4, Although it is also possible to end up in the setting of the 60s Completed within the time limit, But the overall time is getting longer, The phenomenon is request The interface request time is very long. In the client 7.0.10 Version switching Cronet This issue has been resolved

# Certificate issues

Considerations for certificates are documented: https://developers.weixin.qq.com/Minigame /dev/Guide/base-ability/network.html

  1. Certificate expired or invalid

Can be accessed by https://myssl.com /ssl.html Or other online tools, because Android Mobile phone compatibility issues, Validation results do not guarantee that all Android Machines are effective.

  1. Certificate chain incomplete

Android The root certificate is incomplete, If the server is using intermediate certificates, and Android The corresponding root certificate cannot be found on the phone. There will be relevant SSL Error, At this point the server is required to configure the full certificate chain

  1. wss Agreement to go. 80 Port not successful

80 Port correspondence http The default is not to do certificate verification, wss Should be selected 443 interface

# not in Domain url

request url Not in the domain name list, There are several possibilities for encountering this problem

  1. request url not to be present mp In the list of domain names configured
  2. After the redirection url Not in the domain name list
  3. WebSocket The requested port is not configured
  4. Configured domain name not in effect (Very low probability)

# network is down

iOS 14 The system added a local network switch, If closed, the LAN will not work. System interface error network is down, At present, the system does not provide detection switch method. The developer needs to prompt the user to open the permissions based on the error message