颤动:FormatException:解码长流响应时未终止的字符串
flutter: FormatException: Unterminated string while decoding long stream response
我正在开发我制作的 flutter 包 https://github.com/pratikbaid3/flutter_client_sse。这用于使用服务器发送的事件。当返回的响应相对较小时,这很好用。但是一旦响应变大,我就开始收到此错误 flutter: FormatException: Unterminated string
这是用于获取 sse 的代码片段
while (true) {
try {
_client = http.Client();
var request = new http.Request("GET", Uri.parse(url));
request.headers["Cache-Control"] = "no-cache";
request.headers["Accept"] = "text/event-stream";
request.headers["Cookie"] = token;
Future<http.StreamedResponse> response = _client.send(request);
await for (final data in response.asStream()) {
await for (final d in data.stream) {
final rawData = utf8.decode(d);
final event = rawData.split("\n")[1];
if (event != null && event != '') {
yield SSEModel.fromData(rawData);
}
}
}
} catch (e) {
print('---ERROR---');
print(e);
yield SSEModel(data: '', id: '', event: '');
}
await Future.delayed(Duration(seconds: 1), () {});
}
我的猜测是部分响应由于尺寸过大而丢失。
所以经过几个小时的调试,我发现在我目前的方法中,当响应非常大时,一部分是截断(不知道为什么)。我将代码更改为一次读取一行并让它工作。
data.stream
..transform(Utf8Decoder())
.transform(LineSplitter())
.listen((dataLine) {
//Do what you want with the data here
}
这似乎解决了问题。
完整的代码可以在 https://github.com/pratikbaid3/flutter_client_sse
找到
我正在开发我制作的 flutter 包 https://github.com/pratikbaid3/flutter_client_sse。这用于使用服务器发送的事件。当返回的响应相对较小时,这很好用。但是一旦响应变大,我就开始收到此错误 flutter: FormatException: Unterminated string
这是用于获取 sse 的代码片段
while (true) {
try {
_client = http.Client();
var request = new http.Request("GET", Uri.parse(url));
request.headers["Cache-Control"] = "no-cache";
request.headers["Accept"] = "text/event-stream";
request.headers["Cookie"] = token;
Future<http.StreamedResponse> response = _client.send(request);
await for (final data in response.asStream()) {
await for (final d in data.stream) {
final rawData = utf8.decode(d);
final event = rawData.split("\n")[1];
if (event != null && event != '') {
yield SSEModel.fromData(rawData);
}
}
}
} catch (e) {
print('---ERROR---');
print(e);
yield SSEModel(data: '', id: '', event: '');
}
await Future.delayed(Duration(seconds: 1), () {});
}
我的猜测是部分响应由于尺寸过大而丢失。
所以经过几个小时的调试,我发现在我目前的方法中,当响应非常大时,一部分是截断(不知道为什么)。我将代码更改为一次读取一行并让它工作。
data.stream
..transform(Utf8Decoder())
.transform(LineSplitter())
.listen((dataLine) {
//Do what you want with the data here
}
这似乎解决了问题。 完整的代码可以在 https://github.com/pratikbaid3/flutter_client_sse
找到