问题:flutter开发TCP客户端时,收不到服务端发送的数据,主要表现为 if (buff.length >= totalLen) 这条判断无法执行,导致运行不到 onData!(this, cmd);所以,客户端收不到服务端的数据。而且我看网上接收socket消息时都是这么处理的,所以不知道怎么处理了(如果有flutter开发TCP的源码可以提供就更感谢了,最好是源码)
部分代码:
_onData(Uint8List event) async {
debugPrint('----------> $event type=${event.runtimeType}');
// buff = event;
buff += event;
print("TCP客户端接收到的数据是:${buff}");
debugPrint('当前的缓冲区长度为: ${buff.length}');
while (buff.length > 2) {
int packLen = 0;
List<int> lenBuf = buff.sublist(0, 2);
Uint8List tmp = Uint8List.fromList(lenBuf);
ByteData tmpByteData = ByteData.sublistView(tmp);
packLen = tmpByteData.getUint16(0);
debugPrint('lenBuf长度: $lenBuf');
debugPrint('packLen长度: $packLen');
var totalLen = packLen + 2;
debugPrint('totalLen长度: $totalLen');
if (buff.length >= totalLen) {
List<int> curFrame = buff.sublist(2, totalLen);
List<int> packed = buff.sublist(2, 2 + packLen);
debugPrint("数据满足条件 ${buff.length}");
buff.replaceRange(0, totalLen, []);
debugPrint("json解码数据长度 ${packed.length}");
var decoded = utf8.decode(packed);
String cmd = jsonDecode(decoded);
debugPrint("json------------> data= $cmd");
onData!(this, cmd);
debugPrint("数据剩余长度 ${buff.length}");
} else {
debugPrint("数据长度不足 ${buff.length}");
break;
}
}
}
debug页面:
I/flutter (24579): ----------> [49, 50, 49, 50, 49, 50, 49, 50] type=Uint8List
I/flutter (24579): TCP客户端接收到的数据是:[49, 50, 49, 50, 49, 50, 49, 50, 49, 50, 49, 50, 49, 50, 49, 50]
I/flutter (24579): 当前的缓冲区长度为: 16
I/flutter (24579): lenBuf长度: [49, 50]
I/flutter (24579): packLen长度: 12594
I/flutter (24579): totalLen长度: 12596
I/flutter (24579): 数据长度不足 16
如果取消判断限制,则提示:
E/flutter (24579): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: RangeError (end): Invalid value: Not in inclusive range 2..8: 12596
E/flutter (24579): #0 RangeError.checkValidRange (dart:core/errors.dart:363:9)
E/flutter (24579): #1 List.sublist (dart:core-patch/growable_array.dart:84:38)
E/flutter (24579): #2 SocketClient._onData (package:tcpsocket/tcpsocket.dart:170:35)
E/flutter (24579): #3 SocketClient.connect.. (package:tcpsocket/tcpsocket.dart:89:9)
如果持续累加,知道判断条件满足,同样会报上述错误
编译环境:Android studio