I am trying to build a flutter app to send files to any device over my local network. I'm using sockets to send and recieve the data. The transfer is successful but the whole process is very resource(RAM) intensive(I believe because of the Uint8List and builder that is created on the server and client side.)
Because of it I can only send files of size 100-200 MB's without running out of memory. I was wondering whether it was possible to send data more efficiently by optimizing the code or any other method of file transfer altogether.
Server side code:
import 'dart:io';
import 'dart:typed_data';
void main() async {
final server = await ServerSocket.bind('localhost', 2714);
server.listen((client) {
handleClient(client);
});
}
void handleClient(Socket client) async {
File file = File('1.zip');
Uint8List bytes = await file.readAsBytesSync();
print("Connection from:"
"${client.remoteAddress.address}:${client.remotePort}");
client.listen((Uint8List data) async {
await Future.delayed(Duration(seconds: 1));
final request = String.fromCharCodes(data);
if (request == 'Send Data') {
client.add(bytes);
}
client.close();
});
}
Client side code:
import 'dart:io';
import 'dart:typed_data';
int size = 0;
void main() async {
final socket = await Socket.connect('localhost', 2714);
print("Connected to:" '${socket.remoteAddress.address}:${socket.remotePort}');
socket.write('Send Data');
await socket.listen((Uint8List data) async {
await Future.delayed(Duration(seconds: 1));
dataHandler(data);
size = size + data.lengthInBytes;
print(size);
print("ok: data written");
});
await Future.delayed(Duration(seconds: 20));
socket.close();
socket.destroy();
}
BytesBuilder builder = new BytesBuilder(copy: false);
void dataHandler(Uint8List data) {
builder.add(data);
if (builder.length <= 1049497288) {
// file size
Uint8List dt = builder.toBytes();
writeToFile(
dt.buffer.asUint8List(0, dt.buffer.lengthInBytes), '1(recieved).zip');
}
}
Future<void> writeToFile(Uint8List data, String path) {
// final buffer = data.buffer;
return new File(path).writeAsBytes(data);
}
I'm still very much new to Dart and Flutter, any help would be appreciated, thanks.