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, networkOptions: roomOptions.networkOptions);
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 sdkHttpHead(Uri.parse(toHttpUrl(regionUrl)), networkOptions: roomOptions.networkOptions);
logger.fine('prepared connection to ${regionUrl}');
}
} else {
await sdkHttpHead(Uri.parse(toHttpUrl(url)), networkOptions: roomOptions.networkOptions);
}
} catch (e) {
logger.warning('could not prepare connection: $e');
}
}