Search code examples
socketsflutterdarttcpsocket

Flutter - Dart Socket reads half message


I'm developing a Flutter App that receives data in JSON format from a Scala server.
Everything works well, but sometimes I get an incomplete message.

I'm using a Streambuilder to handle the process, with this code:

return StreamBuilder(
      stream: Utils.socket,
      builder: (_, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            body: Center(
              child: AdaptiveSpinner(
                withMessage: 'Connecting to game server',
              ),
            ),
          );
        }

        if (snapshot.error != null) {
          return NetworkErrorScreen();
        }

        final message = String.fromCharCodes(snapshot.data);
[...]
);

In a normal behaviour, String.fromCharCodes(snapshot.data); gives me a valid JSON, that I then parse, etc...but sometimes it happes that the json is incomplete (The socket reads only a portion of it, starting from the beginning until an undefined point, or starting from an undefined point to the end of the same json).

Any ideas on how to solve this issue? Might be related to a buffer size problem? Please help!


Solution

  • We finally manage to solve the issue. We don't know why, but since the server was returning a well formatted json (with line breaks and tabs), this was sometimes giving the error in the question. As soon as we didn't format the json in the server, returning it as a plain string, the error went away itself... It is a mistery for me, if anyone has an explanation, answers are well accepted as correct answers. Thank you!