如何使 WebSocket 连接保持活动状态 - Flutter AWS?

How to keep WebSocket connection Alive - Flutter AWS?

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

我的 WebSocket API 有不同的路由:$connect$disconnectsendMessage。 我想将事件发送到服务器并在 dart 中获得响应。

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

这是我的代码:

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 中所述,我已将 onDoneonError 回调添加到连接后立即调用的代码中。

onError 从未被调用。

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

编辑 2:

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

(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.

收到数据后,连接将关闭。只需重新连接服务器 onDone and/or onError.

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

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