dart-lang / web_socket_channel

StreamChannel wrappers for WebSockets.
https://pub.dev/packages/web_socket_channel
BSD 3-Clause "New" or "Revised" License
410 stars 108 forks source link

Bad state: Stream has already been listened to. #125

Open carlfost opened 3 years ago

carlfost commented 3 years ago

I am getting an error: "Bad state: Stream has already been listened to." message every time I tried to reconnect the webstream when it gets a onDone event. What is the correct way to reconnect the webstream if it gets disconnected?

// configure the websocket Future configWebsocket(int _orgid, int userid, Map<String, dynamic> wsocket) async { String host = wsocket['host'] + _orgid.toString() + wsocket['key']; if (channel == null) { channel = IOWebSocketChannel.connect(host); _listenWebSocket( host); print("SOCKET CHANNEL SET FOR " + _orgid.toString() + " Channel"); } }

void _listenWebSocket( String host) { if (channel != null) { print("CHAT SOCKET LISTENING"); //_controller.stream = channel.stream; // _controller.onListen((data) { Stream _stream = channel.stream.asBroadcastStream(); _stream.listen((data) { // getting bad state error at this line Map<String, dynamic> chatData = json.decode(data); print("WEBSOCKET INCOMING DATA"); ChatCls chatdata = ChatCls.fromMap(chatData); }, onError: (err) { print(new DateTime.now().toString() + " Connection error: $err"); }, onDone: () async { channel = IOWebSocketChannel.connect(host); await Future.delayed(Duration(seconds: 4)); _listenWebSocket( host); }); } else { print("CHAT SOCKET NOT LISTENING"); } } }

matthewchung74 commented 2 years ago

@carlfost did you ever have any luck with this?

justatipfromthedeadsequoiatree commented 2 years ago

@carlfost did you ever have any luck with this?

https://stackoverflow.com/a/62636805/7972633

Hope this helps, good luck