2

我正在创建一个 Web 套接字流广播,可以在 Flutter 应用程序中跨多个页面访问。代码如下

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

在其他页面上,我正在访问此频道并使用


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();
}

使用上面的代码,我曾经使用 streamBuilder 将所有其他小部件与上面创建的通用蒸汽连接起来。这里的问题是在尝试注销并重新登录时,我使用上面的 connect() 方法来初始化通道流。这样做时出现如下错误

I/flutter (15477):连接请求已发送 I/flutter (15477):错误!无法连接 WS connectWs 错误状态:关闭 I/flutter(15477)后无法添加事件:已发送连接请求 E/flutter(15477):[错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:错误状态:关闭 E/flutter (15477) 后无法添加事件:#0 _StreamController.add (dart:async/stream_controller.dart:623:24)

有什么地方出错了吗?

4

0 回答 0