我想在https://pub.dev/packages/flutter_client_sse包中实现一个重新连接逻辑。http连接保持打开状态并监听服务器端事件。当连接由于某种原因丢失时,客户端应该尝试重新连接。连接丢失时会抛出一个异常,但我无法捕获它。
建立连接的代码:
try {
_client = http.Client();
var request = http.Request("GET", Uri.parse(url));
//Adding headers to the request
request.headers["Cache-Control"] = "no-cache";
request.headers["Accept"] = "text/event-stream";
Future<http.StreamedResponse> response = _client.send(request);
response.onError((e, s) {
Log.e("ERROR!");
throw e.cause ?? e;
});
response.catchError((e) => Log.e("ERROR!"));
response.asStream().listen((data) {
...
});
} catch(e) {
Log.e("ERROR!");
}
字符串
当连接丢失时,会抛出一个异常:
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Connection closed while receiving data
E/flutter (24389): #0 IOClient.send.<anonymous closure> (package:http/src/io_client.dart:49:13)
E/flutter (24389): #1 _invokeErrorHandler (dart:async/async_error.dart:45:24)
E/flutter (24389): #2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:272:9)
E/flutter (24389): #3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:157:13)
E/flutter (24389): #4 _HttpClientResponse.listen.<anonymous closure> (dart:_http/http_impl.dart:712:16)
E/flutter (24389): #5 _rootRunBinary (dart:async/zone.dart:1378:47)
E/flutter (24389): #6 _CustomZone.runBinary (dart:async/zone.dart:1272:19)
E/flutter (24389): #7 _CustomZone.runBinaryGuarded (dart:async/zone.dart:1178:7)
型
我怎么能抓住这个借口做重新连接?
2条答案
按热度按时间7rtdyuoh1#
你需要
await
在try
catch
块中的响应来捕获http错误,我修改了你的代码一点第一个
try
块字符串
第二个
catch
块你需要检查
catch
块上的错误类型,在你的例子中是ClientException
型
然后您可以检查错误消息
型
qlzsbp2j2#
感谢7mada的回复。这是我用他的解决方案实现的:
字符串