57 lines
1.8 KiB
C#
57 lines
1.8 KiB
C#
using Microsoft.AspNetCore.Components;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
|
|
|
namespace FruitBankHybrid.Shared.Services
|
|
{
|
|
|
|
public class SignalRService : IAsyncDisposable, ISignalRService
|
|
{
|
|
private HubConnection _hubConnection;
|
|
private readonly NavigationManager _navigationManager;
|
|
|
|
public event Action<string, string>? MessageReceived;
|
|
|
|
public SignalRService(NavigationManager navigationManager)
|
|
{
|
|
_navigationManager = navigationManager;
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
// Build the connection (assuming same domain as Blazor app, otherwise use full URL)
|
|
_hubConnection = new HubConnectionBuilder()
|
|
.WithUrl(_navigationManager.ToAbsoluteUri("https://localhost:59579/fbhub/"))
|
|
//.WithUrl(_navigationManager.ToAbsoluteUri("http://10.0.2.2:59580/fbhub"))
|
|
.WithAutomaticReconnect()
|
|
.Build();
|
|
|
|
// Register incoming handler
|
|
_hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
|
|
{
|
|
MessageReceived?.Invoke(user, message);
|
|
});
|
|
|
|
await _hubConnection.StartAsync();
|
|
}
|
|
|
|
public async Task SendMessageAsync(string user, string message)
|
|
{
|
|
if (_hubConnection.State == HubConnectionState.Connected)
|
|
await _hubConnection.InvokeAsync("SendMessage", user, message);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (_hubConnection is not null)
|
|
{
|
|
await _hubConnection.DisposeAsync();
|
|
}
|
|
}
|
|
}
|
|
}
|