首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让服务器发送事件在我的颤栗应用程序?

如何让服务器发送事件在我的颤栗应用程序?
EN

Stack Overflow用户
提问于 2021-02-10 20:28:16
回答 2查看 2.9K关注 0票数 1

我正试图在我的应用程序中以JSON的形式接收SSE数据。但是,不是获取数据,而是在我的控制台中得到以下重复的数字数组。

代码语言:javascript
复制
    I/flutter (17286): Received streamedResponse.statusCode:200
    I/flutter (17286): Received data:[100, 97, 116, 97, 58, 32, 123, 34, 109, 115, 103, 34, 58, 34, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, 10, 10]
    I/flutter (17286): Received data:[100, 97, 116, 97, 58, 32, 123, 34, 109, 115, 103, 34, 58, 34, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, 10, 10]

以下是服务器上SSE数据的样子

代码语言:javascript
复制
data: {"msg":"This is my message"}
data: {"msg":"This is my message"}
data: {"msg":"This is my message"}
    (repeated over and over)

这是颤振代码;

代码语言:javascript
复制
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

 class MyApp extends StatelessWidget {
 http.Client _client;

  MyApp() : super() {
         subscribe();
   }

  @override
    Widget build(BuildContext context) {
       return MaterialApp(
     title: 'Flutter SSE',
     home: Scaffold(
      appBar: AppBar(
      title: Text('Receive SSE Events'),
    ),
    body: Center(
      child: Text('Ready for events..'),
    ),
   ),
 );
}

subscribe() async {
  print("Subscribing..");
  try {
   _client = http.Client();

  var request = new http.Request("GET", Uri.parse("http://18.224.97.18:8080/connect"));
  request.headers["Cache-Control"] = "no-cache";
  request.headers["Accept"] = "text/event-stream";

  Future<http.StreamedResponse> response = _client.send(request);

  response.asStream().listen((streamedResponse) {
    print("Received streamedResponse.statusCode:${streamedResponse.statusCode}");
    streamedResponse.stream.listen((data) {
      print("Received data:$data");
    });

  });
} catch(e) {
  print("Caught $e");
  }
}

 unsubscribe() {
   _client.close();
      }
     }

我不知道为什么"print("Received data:$data")要在SSE流中提供数字数组而不是{"msg":"This is my message"}

有人知道我为什么要得到这些数字而不是数据吗?

EN

回答 2

Stack Overflow用户

发布于 2022-07-05 13:05:43

ByteStream是从streamedResponse.stream.listen()返回的data。要解码这个值,您可以像注释中提到的那样使用utf8.decode(data)

票数 0
EN

Stack Overflow用户

发布于 2022-11-21 10:20:07

对服务器发送的事件流数据使用sse包。它返回事件、id和数据的解析模型。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66144533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档