【发布时间】: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