Cosmin
Cosmin

Reputation: 21426

Flutter Socket.listen() receives incomplete data

Using a socket to receive string data. And it seems like the transmission is incomplete. The server sends around 80 KB and the flutter socket receives sometimes 1 KB and sometimes around 10 KB.

Tried the onDone() handler and it's the same. It's called before the whole data is received.

I also tried breaking the data into multiple pieces. And I get the first and the last packet, but lose everything between.

Is this broken? Here is my code:

Future<String> getNetworkData() async {
  String rawData;
  await Socket.connect(ipAddr, port).then((Socket socket) {
    socket.add(utf8.encode(request));
    socket.listen((var data) {
      rawData = utf8.decode(data);
    });

  return rawData;
}

Upvotes: 2

Views: 3402

Answers (1)

Richard Heap
Richard Heap

Reputation: 51731

The anonymous function that you are passing to listen is going to be called multiple times with chunks of the response. It's up to you to concatenate them. As you need a string you can use the stream join convenience function.

Future<String> getNetworkData() async {
  Socket s = await Socket.connect(ipAddr, port);
  s.add(utf8.encode(request));
  String result = await s.transform(utf8.decoder).join();
  await s.close(); // probably need to close the socket
  return result;
}

This assumes that the server will close the socket when it's finished sending. If you want to reuse the socket then you need to agree a scheme with the server so that you know when it has finished sending. It could tell you at the beginning the length, or you could parse the data as it arrives. This is the same for anyone reading from a tcp socket - regardless of language.

Aside - any time you see await and then on the same line, be suspicious. It can probably be simplified.

Upvotes: 1

Related Questions