-
Notifications
You must be signed in to change notification settings - Fork 86
/
ChatService.cs
43 lines (34 loc) · 1.13 KB
/
ChatService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using Microsoft.AspNetCore.SignalR.Client;
namespace SignalRSimpleChat;
public class ChatService( ILogger<ChatService> logger ) : IAsyncDisposable
{
private HubConnection _connection;
private readonly ILogger _logger = logger;
public async Task ConnectAsync()
{
_connection = new HubConnectionBuilder()
.WithUrl( $"https://localhost:5001{ChatHub.HubUrl}" )
.Build();
_connection.On<string, string>( ChatHub.SendToAllClient, (user, message) =>
{
OnSendToAllMessage.Invoke( user, message );
} );
if ( _connection.State != HubConnectionState.Connected )
{
await _connection.StartAsync( );
}
}
public Action<string, string> OnSendToAllMessage { get; set; }
public async Task SendToAll(string sender, string message)
{
var serverMethodName = nameof( ChatHub.SendToAll );
await _connection.InvokeAsync( serverMethodName, sender, message );
}
public async ValueTask DisposeAsync()
{
if ( _connection != null )
{
await _connection.DisposeAsync( );
}
}
}