flutter - 将 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();
}
}
我哪里出错了请帮忙。
解决方案
推荐阅读
- php - Laravel Excel 和打印断行
- python - AWS X-Ray Python:MissingEndTime 错误
- java - rest api 下载文件返回文件内容作为响应而不下载它
- angular - 如何在单个项目中运行angular和angular js框架
- javascript - connect.bodyParser 不是函数
- python - 文件上传到 Python 中的 Google Cloud Storage 签名 URL
- wordpress - CF7 下拉菜单上的 OnChange 事件 [选择]
- mysql - 我们 DBA 对 MySQL 和 TiDB 的性能测试表明,独立的 TiDB 的性能不如 MySQL
- c# - 如何在 C# 中对 TextBox 进行约束?
- javascript - 如何将工具提示添加到锚点