【问题标题】:How to keep WebSocket connection Alive - Flutter AWS?如何保持 WebSocket 连接活动 - Flutter AWS?
【发布时间】:2021-10-21 22:32:15
【问题描述】:

我正在尝试从我的 Flutter 应用程序连接到托管在 AWS 中的 Websocket API。
我正在使用web_socket_channel 包来构建一个实时聊天应用程序。

我的 WebSocket API 有不同的路由:$connect、$disconnect 和 sendMessage。 我想向服务器发送事件并在 dart 中获得响应。

到目前为止,我没有办法调试它,因为 web_socket_channel 不提供这种可能性......所以我根本没有接收事件也没有发送它们(我的 CloudWatch 日志组中没有日志,而我有一些使用wscat 或邮递员工具都可以正常工作)。

这是我的代码:

print("Connecting to websocket...");
    try {
      IOWebSocketChannel channel = IOWebSocketChannel.connect(
        Uri.parse('wss://my_websocket_endpoint'),
      );
      print("Protocol : ${channel.protocol}");
      channel.stream.listen((message) {
        print("Message is : $message");
        //channel.sink.add('received!');
        //channel.sink.close(goingAway);
      },
        onDone: () {
          print("Disconnected, done.");
          print("Close reason : ${channel.closeReason}");
          print("Close code : ${channel.closeCode}");
        },
        onError: (error) {
          print("Error listening : $error");
        },
      );
      channel.sink.add({"action": "sendMessage", "data": "test"});
    }
    catch (error) {
      print("Error connecting : $error");
    }

查看和清理日志后,我意识到上面的代码调用了$connect 路由,100 毫秒后调用了$disconnect 路由。

因此导致答案是:为什么连接不保持活动状态? (我没有关闭dart 中的任何内容,这是我处理套接字的唯一一段代码)

编辑:

正如answer 中所述,我已将onDone 和onError 回调添加到连接后立即调用的代码中。

onError 永远不会被调用。

为什么会这样?其他工具何时保持连接?

编辑 2:

我在此处添加 API Gateway 中的连接日志:

(clientID=) Client [Connection Id: clientID=] disconnected from API [apiID] with integration response status code [200]. Close reason: [1006: Connection closed abnormally]

根据website:

LWS_CLOSE_STATUS_ABNORMAL_CLOSE     
1006 is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint. It is designated for use in applications expecting a status code to indicate that the connection was closed abnormally, e.g., without sending or receiving a Close control frame.

而客户端我已经捕获了状态码1005:

LWS_CLOSE_STATUS_NO_STATUS  
1005 is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint. It is designated for use in applications expecting a status code to indicate that no status code was actually present.

【问题讨论】:

  • 你能把集团代码也贴出来吗?
  • 感谢您的评论,我已经编辑了答案

标签: amazon-web-services flutter dart websocket aws-api-gateway


【解决方案1】:

在将数据传递给请求之前,您需要“字符串化”数据。
body 应该是一个字符串,因此您可以使用:

channel.sink.add(jsonEncode({"action": "sendMessage", "data": "test"}));

【讨论】:

    【解决方案2】:

    当接收到数据时,连接关闭。只需重新连接服务器 onDone 和/或 onError。

    【讨论】:

    • 感谢您的回答。但是我实际上没有收到任何数据...根据您的回答,我似乎不了解 Websocket 是如何工作的,它需要在每次事件后重新连接并且没有保持活动状态...是这个包需要做这种事?
    • 如果这有助于改善您的答案,我已将问题更新为关闭代码状态。目前,不幸的是,如果我再次尝试连接,它会一直关闭,这并不能解决这个问题。
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2012-01-03
    • 2019-07-19
    • 1970-01-01
    • 2021-06-11
    • 2017-05-03
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多