Error during streaming: HttpException: Connection closed while receiving data. in Flutter

70 views Asked by At

I've already checked online but i didn't found the solution.

  1. I Have a node js server that performe a query on a SQL DB Streaming the response.
  2. I Have a flutter app that try to read that stream but give me this error after a while.

All codes I tried I received alwais the same error, with also with a cURL except when I use this: curl --no-buffer --http1.0 http://192.168.100.172:5000/initdbclient/mbanag/

I tried to do the same call with Flutter but I could not.

some one can help?

below the code:

Node JS SERVER

exports.syncMBAnag=async function(req,res) {
    console.log(req);
    try{
        await sqlDb.connect(settings.dbConfig);
        const query2=`SELECT FTAR_ID,
        FTAR_FTAN_ID,
        FTAR_NumRiga,
        FTAR_MGAA_ID,
        FTAR_Descr,
        FTAR_Quantita,
        FTAR_MBUM_Codice,
        FTAR_Prezzo,
        FTAR_TotSconti,
        FTAR_ScontiFinali,
        FTAR_Note,
        FTAR_DQTA,
        FTAR_RivalsaIva FROM FT_Artic`;
 
        const request=new sqlDb.Request();
        request.stream=true;
        request.query(query2);
        console.info('Start Stream');
        let i =0;
         request.on('row', row => {
           
            res.write(JSON.stringify(row) + '\n');
        });

        // Evento 'error'
        request.on('error', err => {
            console.error(err);
            res.status(500).send('Errore durante il recupero dei dati');
        });

        // Evento 'done' alla fine dello streaming
        request.on('done', () => {
            console.info('End Stream');
            res.end();
        });
    }
    catch(err){
        console.error(err);
        res.status(500).send('Errore di connessione al database');
    }
}

FLUTTER

Version 1

 try {
      final url = Uri.parse('http://192.168.100.172:5000/initdbclient/mbanag');
      final client = http.Client();
      final Map<String, String> httpHeaders = {
        HttpHeaders.contentTypeHeader: "application/json",
        "Connection": "Keep-Alive",
        "Keep-Alive": "timeout=5, max=1000",
        'Accept-Encoding': 'gzip, deflate, br',
        'Cache-Control': 'no-cache',
        'Accept': "text/event-stream"
      };

      final request = http.Request('GET', url);
      request.headers.addAll(httpHeaders);
      final response = await client.send(request);

      response.stream
          .transform(utf8.decoder)
          .transform(const LineSplitter())
          .listen((line) {
        var data = json.decode(line);
        print(data);
      }, onError: (e, s) {
        printError(info: 'onError: $e');
        printInfo(info: 's: $s');
      });
    } catch (e) {
      print("Error: $e");
    }

Version 2

final url = Uri.parse('http://192.168.100.172:5000/initdbclient/mbanag');
    var httpClient = HttpClient();

    try {
      // Configurare il client per usare HTTP/1.0
      httpClient.userAgent = 'HTTP/1.0';

      var request = await httpClient.getUrl(url);
      request.headers
        ..set(HttpHeaders.contentTypeHeader, "application/json")
        ..set(HttpHeaders.connectionHeader, "Keep-Alive")
        ..set(HttpHeaders.acceptEncodingHeader, 'gzip, deflate, br');

      var response = await request.close();
      // Leggere lo stream di dati
      await for (var data in response.transform(utf8.decoder)) {
        // Elaborare ogni pezzo di dati ricevuto
        print(data);
      }
    } catch (e) {
      print("Error: $e");
    } finally {
      httpClient.close();
    }

Version 3 Using DIO

var dioClient = dio.Dio();
    var url = 'http://192.168.100.172:5000/initdbclient/mbanag/';

    try {
      // Configurare Dio per usare HTTP/1.0
      dioClient.options.headers["user-agent"] = "HTTP/1.0";

      // Effettuare la richiesta GET e ascoltare lo stream di risposta
      dio.Response<dio.ResponseBody> response =
          await dioClient.get<dio.ResponseBody>(
        url,
        options: dio.Options(
            responseType: dio.ResponseType.stream,
            followRedirects: false,
            validateStatus: (status) {
              return status! < 500;
            }),
      );
      response.data!.stream.transform(StreamTransformer.fromHandlers(
        handleData: (data, sink) {
          sink.add(utf8.decode(data));
        },
      )).listen(
        (data) {
          // Elabora ogni pezzo di dati ricevuto
          print(data);
        },
        onError: (e) {
          print('Errore durante lo streaming: $e');
        },
        onDone: () {
          print('Streaming completato');
        },
      );
    } catch (e) {
      print('Errore durante la richiesta: $e');
    }
0

There are 0 answers