mirror of
https://github.com/ryzij/AMessanger-Avalonia-Client.git
synced 2026-09-18 20:13:20 +00:00
49 lines
1.3 KiB
C#
49 lines
1.3 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
|
|
|
namespace AMessanger.Services;
|
|
|
|
public class ChatService
|
|
{
|
|
private readonly HubConnection _connection;
|
|
|
|
public event Action<string, string>? OnMessageRecieved;
|
|
|
|
public bool IsConnected { get; private set; } = false;
|
|
|
|
public ChatService(string url)
|
|
{
|
|
_connection = new HubConnectionBuilder()
|
|
.WithUrl(url)
|
|
.WithAutomaticReconnect()
|
|
.Build();
|
|
|
|
_connection.On<string, string>("ReceiveMessage", (user, message) =>
|
|
OnMessageRecieved?.Invoke(user, message));
|
|
}
|
|
|
|
public Task ConnectAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
if (IsConnected)
|
|
return Task.CompletedTask;
|
|
|
|
IsConnected = true;
|
|
return _connection.StartAsync(cancellationToken);
|
|
}
|
|
|
|
public Task DisconnectAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
if (!IsConnected)
|
|
return Task.CompletedTask;
|
|
|
|
IsConnected = false;
|
|
return _connection.StopAsync(cancellationToken);
|
|
}
|
|
|
|
public Task SendMessageAsync(string user, string message, CancellationToken cancellationToken = default)
|
|
{
|
|
return _connection.InvokeAsync("SendMessage", user, message, cancellationToken);
|
|
}
|
|
} |