首页 > 解决方案 > 将 SignalR 与 Flutter 一起使用时循环 OnConnected

问题描述

我正在构建一个简单的聊天应用程序。技术包括:.Net 5、angular、Flutter。实时使用 SignalR。.Net 5 和 Angular 一切正常。我在 pub.dev 上为 Flutter 使用 signalr_netcore 1.0.1 在应用程序中,当我登录服务器时,循环出现在服务器上。OnConnectedAsync 和 OnDisconnectedAsync 被连续调用而不在服务器上停止。.Net 代码中心:

public override async Task OnConnectedAsync()
        {
            var isOnline = await _tracker.UserConnected(Context.User.GetUsername(), Context.ConnectionId);
            if (isOnline)
                await Clients.Others.SendAsync("UserIsOnline", Context.User.GetUsername());

            var currentUsers = await _tracker.GetOnlineUsers();
            await Clients.Caller.SendAsync("GetOnlineUsers", currentUsers);
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var isOffline = await _tracker.UserDisconnected(Context.User.GetUsername(), Context.ConnectionId);
            if (isOffline)
                await Clients.Others.SendAsync("UserIsOffline", Context.User.GetUsername());

            await base.OnDisconnectedAsync(exception);
        }

这是我的颤振集线器连接功能:

class UserController extends GetxController {
  var users = List<Member>().obs;
  HubConnection _hubConnection;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    fetchUsers();
  }

  createHubConnection() {
    if (_hubConnection == null) {
      _hubConnection = HubConnectionBuilder()
          .withUrl(hubUrl + "presence",
          options: HttpConnectionOptions(
              accessTokenFactory: () async => Globals.user.token))
          .build();

      _hubConnection.onclose(({error}) => print("Connection Closed"));

      if (_hubConnection.state != HubConnectionState.Connected) {
        _hubConnection
            .start()
            .catchError((e) => {
          print("PresenceService at Start: "+ e.toString())
        });
      }

      _hubConnection.on("UserIsOnline", _userIsOnline);
      _hubConnection.on("UserIsOffline", _userIsOffline);
      _hubConnection.on("GetOnlineUsers", _getOnlineUsers);
      _hubConnection.on("NewMessageReceived", _newMessageReceived);
    }
  }

  stopHubConnection(){
    _hubConnection.stop().catchError((e) => {
      print("PresenceService at Stop: "+ e.toString())
    });
  }
}

我在聊天页面外调用 createHubConnection:

class _ChatPageState extends State<ChatPage> {
  final userController = Get.put(UserController());
  bool isOneTime = false;

  @override
  void initState() {
    // TODO: implement initState
    userController.fetchUsers();

    if(!isOneTime){
      userController.createHubConnection();
      isOneTime = true;
    }

    super.initState();
  }
}

我哪里出错了请帮忙。

标签: flutter

解决方案


推荐阅读