我正在努力如何实现 websockets
flutter 中的自动重新连接。我用 web_socket_channel ,但是,插件只是包装 dart.io WebSocket ,因此任何基于 WebSocket
的解决方案类(class)也对我有用。
我已经想通了,如何捕获套接字断开连接,请参见下面的代码片段:
try {
_channel = IOWebSocketChannel.connect(
wsUrl,
);
///
/// Start listening to new notifications / messages
///
_channel.stream.listen(
_onMessageFromServer,
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
debugPrint('ws error $error');
},
);
} catch (e) {
///
/// General error handling
/// TODO handle connection failure
///
debugPrint('Connection exception $e');
}
我想调用
IOWebSocketChannel.connect
来自onDone
,但是,这会导致一种无限循环 - 因为我必须关闭 _channel
事先调用connect
再次,这轮到 onDone
再等等。任何帮助将不胜感激!
最佳答案
使用 package:web_socket_channel (IOWebSocketChannel) 没有任何方法可以实现套接字连接的重新连接。但是您可以使用 WebSocket 类来实现可重新连接的连接。
您可以实现 WebSocket channel ,然后使用 StreamController 类广播消息。工作示例:
import 'dart:async';
import 'dart:io';
class NotificationController {
static final NotificationController _singleton = new NotificationController._internal();
StreamController<String> streamController = new StreamController.broadcast(sync: true);
String wsUrl = 'ws://YOUR_WEBSERVICE_URL';
WebSocket channel;
factory NotificationController() {
return _singleton;
}
NotificationController._internal() {
initWebSocketConnection();
}
initWebSocketConnection() async {
print("conecting...");
this.channel = await connectWs();
print("socket connection initializied");
this.channel.done.then((dynamic _) => _onDisconnected());
broadcastNotifications();
}
broadcastNotifications() {
this.channel.listen((streamData) {
streamController.add(streamData);
}, onDone: () {
print("conecting aborted");
initWebSocketConnection();
}, onError: (e) {
print('Server error: $e');
initWebSocketConnection();
});
}
connectWs() async{
try {
return await WebSocket.connect(wsUrl);
} catch (e) {
print("Error! can not connect WS connectWs " + e.toString());
await Future.delayed(Duration(milliseconds: 10000));
return await connectWs();
}
}
void _onDisconnected() {
initWebSocketConnection();
}
}
因为通知 Controller 返回一个单例实例,所以服务器和设备之间总是会有一个 Socket 连接。并且通过StreamController的广播方式,我们可以在多个消费者之间共享Websocket发送的数据var _streamController = new NotificationController().streamController;
_streamController.stream.listen(pushNotifications);
关于websocket - flutter websockets autoreconnect - 如何实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503083/