TourIAm/TIAMWebApp/Shared/Services/SignalRService.cs

74 lines
2.1 KiB
C#

using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;
using TIAMWebApp.Shared.Application.Models.ClientSide;
namespace TIAMWebApp.Shared.Application.Services
{
public class SignalRService
{
private HubConnection _hubConnection;
public event Action<string, string> OnMessageReceived;
public event Action<string> OnUserMuted;
public event Action<string> OnUserLoggedIn;
public event Action<string> OnUserLoggedOut;
public async Task StartConnection(string userName)
{
_hubConnection = new HubConnectionBuilder()
.WithUrl($"{Setting.BaseUrl}/myhub")
.Build();
_hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
OnMessageReceived?.Invoke(user, message);
});
_hubConnection.On<string>("UserMuted", (user) =>
{
OnUserMuted?.Invoke(user);
});
_hubConnection.On<string>("UserLoggedInToChat", (user) =>
{
OnUserLoggedIn?.Invoke(user);
});
_hubConnection.On<string>("UserLoggedOutFromChat", (user) =>
{
OnUserLoggedOut?.Invoke(user);
});
await _hubConnection.StartAsync();
await LoggedInToChat(userName);
}
public async Task SendMessage(string user, string message)
{
await _hubConnection.SendAsync("SendMessage", user, message);
}
public async Task MuteChat(string user)
{
await _hubConnection.SendAsync("MuteChat", user);
}
public async Task LoggedInToChat(string user)
{
await _hubConnection.SendAsync("LoggedInToChat", user);
}
public async Task LoggedOutFromChat(string user)
{
await _hubConnection.SendAsync("LoggedOutFromChat", user);
}
public async Task StopConnection()
{
await _hubConnection.StopAsync();
await _hubConnection.DisposeAsync();
}
}
}