prepareConnection method
prepareConnection should be called as soon as the page is loaded, in order to speed up the connection attempt. This function will
- perform DNS resolution and pre-warm the DNS cache
- establish TLS connection and cache TLS keys
With LiveKit Cloud, it will also determine the best edge data center for the current client to connect to if a token is provided.
Implementation
Future<void> prepareConnection(String url, String? token) async {
if (engine.connectionState != ConnectionState.disconnected) {
return;
}
logger.info('prepareConnection to $url');
try {
if (isCloudUrl(Uri.parse(url)) && token != null) {
_regionUrlProvider = RegionUrlProvider(token: token, url: url);
final regionUrl = await _regionUrlProvider!.getNextBestRegionUrl();
// we will not replace the regionUrl if an attempt had already started
// to avoid overriding regionUrl after a new connection attempt had started
if (regionUrl != null && connectionState == ConnectionState.disconnected) {
_regionUrl = regionUrl;
await http.head(Uri.parse(toHttpUrl(regionUrl)));
logger.fine('prepared connection to ${regionUrl}');
}
} else {
await http.head(Uri.parse(toHttpUrl(url)));
}
} catch (e) {
logger.warning('could not prepare connection');
}
}