此方法提交一个简单的HTTP请求并调用成功或错误回调就好了:
This method submits a simple HTTP request and calls a success or error callback just fine:
void _getSimpleReply( String command, callback, errorCallback ) async { try { HttpClientRequest request = await _myClient.get( _serverIPAddress, _serverPort, '/' ); HttpClientResponse response = await request.close(); response.transform( utf8.decoder ).listen( (onData) { callback( onData ); } ); } on SocketException catch( e ) { errorCallback( e.toString() ); } }如果服务器未运行,Android应用或多或少会立即调用errorCallback。
If the server isn't running, the Android-app more or less instantly calls the errorCallback.
在iOS上,errorCallback会花费很长的时间-超过20秒-直到获得任何回调
On iOS, the errorCallback takes a very long period of time - more than 20 seconds - until any callback gets called.
我可以为HttpClient()设置等待服务器端返回回复的最大秒数-如果有的话?
推荐答案有两种不同的方法可以在Dart中配置此行为
There are two different ways to configure this behavior in Dart
您可以使用 Future.timeout 方法。在给定的持续时间过去之后,这将通过引发 TimeoutException 来短路。
try { final request = await client.get(...); final response = await request.close() .timeout(const Duration(seconds: 2)); // rest of the code ... } on TimeoutException catch (_) { // A timeout occurred. } on SocketException catch (_) { // Other exception }在HttpClient上设置超时
您还可以使用 HttpClient.connectionTimeout 。设置超时后,这将应用于同一客户端发出的所有请求。当请求超过此超时时,将抛出 SocketException 。
final client = new HttpClient(); client.connectionTimeout = const Duration(seconds: 5);更多推荐
设置HTTPClient get()请求的超时
发布评论