Webscoket channel not connecting after closing it - Flutter

1.3k Views Asked by At

I'm creating a web socket stream broadcast that is accessed across multiple pages in a flutter app. The code is as below

class MyApp extends StatelessWidget {
  static IOWebSocketChannel channel =
      IOWebSocketChannel.connect(HttpService.wsUrl);
  static Stream stream = channel.stream.asBroadcastStream();

On other pages, I'm accessing this channel and stream using


onConnected() async {
  MyApp.stream.listen((e) async {
       onMessage(e);
      },
       onDone: () async {
    debugPrint('ws channel closed');
    await onDisconnected();
  }, onError: (error) async {
    // counter = 0;
    debugPrint('ws error $error');
    await onDisconnected();
  });
}

void onMessage(data) async {
  //To Do
  await parseTCPResponse(jsonDecode);
}

//Reconnect websocket in 1 seconds
onDisconnected() async {
   widget.channel.sink.close();
  print("Disconnected, trying again in 2s");
  new Timer(new Duration(seconds: 2), () async {
    await connect();
  });
}

connect() async {
  try {
    IOWebSocketChannel channel = IOWebSocketChannel.connect(HttpService.wsUrl);
    Stream stream = channel.stream.asBroadcastStream();
    await Future.delayed(Duration(milliseconds: 1000));
    await connectionRequest();
  } catch (e) {
    print("Error! can not connect WS connectWs " + e.toString());
    await Future.delayed(Duration(milliseconds: 1000));
    IOWebSocketChannel channel = IOWebSocketChannel.connect(HttpService.wsUrl);
    Stream stream = channel.stream.asBroadcastStream();
    await connectionRequest();
  }
}

@override
void dispose() {
  MyApp.channel.sink.close();
  dispose();
}

Using the above code, I used to connect all other widgets using the streamBuilder with the common steam created above. The problem here is while trying to log out and re-login, I used the above connect() method to initialize the channel stream. While doing so am getting the error as below

I/flutter (15477): Connection Request sent I/flutter (15477): Error! can not connect WS connectWs Bad state: Cannot add event after closing I/flutter (15477): Connection Request sent E/flutter (15477): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Bad state: Cannot add event after closing E/flutter (15477): #0 _StreamController.add (dart:async/stream_controller.dart:623:24)

Any pointers where it is going wrong?

1

There are 1 best solutions below

0
On

I'm facing same problem right now. But I found a solution for that.

You can close the connection and reconnect the web socket before the web socket.listener method.

FOR Example:

void websocketFunction() {
     channel.sink.close();
          channel = WebSocketChannel.connect(
            Uri.parse('wss://12.251.145.12:25008'),
          );
          socketListener= channel.stream.listen((event) async {
            var decodedJson = json.decode(event);
            if (
            decodedJson["data"]["location_id"].toString() ==
                locationId.toString()
                && decodedJson["type"].toString() == "order.created"
            ) {
              Provider.of<OrderProvider>(context, listen: false).getAllOrders(
                  locationId);
            } else {
              debugPrint("not new order " + event.toString());
            }
          });
}