基本上,我试图检查我的WebSocket Server.ws
的状态。然而,当我查询Server.ws.readyState
时,我得到的唯一响应是WebSocket.OPEN
。如果它总是返回WebSocket.OPEN
,我如何检查WebSocket是否断开连接?
例如,我曾尝试关闭用于测试Flutter应用的设备的WiFi。通常情况下,一秒钟后,WebSocket被认为断开连接,并使用WebSocketStatus.GOING_AWAY
关闭代码关闭连接。我认为这也会更改WebSocket.readyState
,但似乎并非如此。
那么,如何正确检查WebSocket的状态?
我目前如何检查:
/// Connection status
IconButton _status() {
IconData iconData;
switch (Server.ws?.readyState) {
case WebSocket.CONNECTING:
print("readyState : CONNECTING");
iconData = Icons.wifi;
break;
case WebSocket.OPEN:
print("readyState : OPEN");
iconData = Icons.signal_wifi_4_bar;
break;
case WebSocket.CLOSING:
print("readyState : CLOSING");
iconData = Icons.signal_wifi_4_bar_lock;
break;
case WebSocket.CLOSED:
print("readyState : CLOSED");
iconData = Icons.warning;
break;
default:
print("readyState : " + Server.ws.readyState.toString());
break;
}
return new IconButton(
icon: new Icon(iconData),
tooltip: 'Connection Status', // TODO:Localize
onPressed: () {
setState(() {
Server.ws.close();
});
},
);
}
有关WebSocket的其他信息:
/// Should be called when the IP is validated
void startSocket() {
try {
WebSocket.connect(Server.qr).then((socket) {
// Build WebSocket
Server.ws = socket;
Server.ws.listen(
handleData,
onError: handleError,
onDone: handleDone,
cancelOnError: true,
);
Server.ws.pingInterval = new Duration(
seconds: Globals.map["PingInterval"],
);
send(
"CONNECTION",
{
"deviceID": Globals.map["UUID"],
},
);
});
} catch (e) {
print("Error opening a WebSocket : $e");
}
}
/// Handles the closing of the connection.
void handleDone() {
print("WebSocket closed.");
new Timer(new Duration(seconds: Globals.map["PingInterval"]), startSocket);
}
/// Handles the WebSocket's errors.
void handleError(Error e) {
print("WebSocket error.");
print(e);
Server.ws.close();
}
2条答案
按热度按时间e37o9pze1#
我已经看了WebSocket实现的源代码。看起来当WebSocket以
GOING_AWAY
状态关闭时,内部套接字流也被关闭。然而,这个事件可能不会传播到处理示例readyState
的转换流。我建议在dartbug.com提交错误报告。a64a0gku2#
尝试设置pingInterval,这将在每个上述间隔检查连接状态,然后closeCode将更新