Flutter:重新创建源时套接字不会收到新消息

问题描述

我正在尝试使用以下实现在 Flutter/Dart 的 WebSockets 中实现自动重新连接:

class WebsocketService {
  IOWebSocketChannel channel;
  Stream stream;
  final BuildContext context;

  bool internetConnection = true;

  WebsocketService(this.context);

  void initialise() {
    if (kDebugMode) print("Connecting to websocket: $juliusURL");
    try {
      this.channel = IOWebSocketChannel.connect("wss://echo.websockets.org");
      this.stream = createStream();
      _finalsetup();
    } on WebSocketChannelException catch (_) {
      // Probably Disconnected
      internetConnection = false;
      // Due to the RecurringTimer below,the app will automatically try to
      // connect again in ~15 sec
    }

    // Checks if the device is still connected to the internet
    RecurringTimer().interval(Duration(seconds: 15),(timer) async {
      try {
        final result = await InternetAddress.lookup(augustusURL.replaceAll('https://',''));
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
          if (internetConnection == false) {
            if (kDebugMode) print("Connected to the internet,reconnecting to websocket");
            reconnect();
            internetConnection = true;
          }
        }
      } on SocketException catch (_) {
        //Disconnected from the internet
        if (kDebugMode) print("Disconnected from the internet");
        closeWebsocket();
        internetConnection = false;
      }
    });
  }

  void closeWebsocket() {
    stream.listen((_){}).cancel();
    channel.sink.close();
  }

  void reconnect() async {
    if (kDebugMode) print("Connection lost,reconnecting");
    // Reconnect
    closeWebsocket();
    channel = IOWebSocketChannel.connect(juliusURL);
    stream = createStream();
    _finalsetup();
  }

  void _finalsetup() {
    if (kDebugMode) print("Sending {\"channel\": \"authentication\",\"sessionId\": \"<sessionID>\"}");
    channel.sink.add(
        "{\"channel\": \"authentication\",\"sessionId\": \"<sessionID>\"}");
    onConnect();
    channel.sink.done.then((error) => {
      if (internetConnection) {
        reconnect()
      }
    });
  }
  
  void onConnect(){
   //This function should be overridden by the class using it 
  }

  // Generic method to create a stream
  // Should be overriden in the specific service
  Stream createStream() {
    StreamController<String> controller;
    StreamSubscription source;

    void processWSMessages() {
      source = channel.stream.listen( (chunk) {
        if (chunk is String) {
          print(chunk);
          controller.add(chunk);
        }
      } );
    }

    void cancelProcessing() {
      source.cancel();
    }

    controller = StreamController<String>(
        onListen: processWSMessages,onCancel: cancelProcessing
    );

    return controller.stream;
  }

  /*
    Open login screen function
   */

  void openLoginScreen() {
    //not important
  }
}

几个函数应该被覆盖,但是这段代码也应该以这种方式工作。 它正常连接到 websocket 就好了(这里我使用 echo.websockets.org 作为测试),但是在调用 reconnect() 时它停止接收消息(这可以通过断开设备与 Internet 的连接来测试,等待以便应用程序检测没有互联网连接,然后再次连接到互联网并让代码运行)。我知道这是因为服务器收到消息,但客户端不会打印服务器发回的消息。

所以我的问题是:这段代码有什么问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...