forked from Ibro/SignalRSimpleChat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatHub.cs
48 lines (40 loc) · 1.22 KB
/
ChatHub.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
44
45
46
47
48
using Microsoft.AspNetCore.SignalR;
namespace SignalRSimpleChat;
public class ChatHub () : Hub
{
public const string HubUrl = "/chathub";
public const string SendToAllClient = "SendToAllClient";
public static Dictionary<string, string> ConnectedUsers = new Dictionary<string, string>();
public static event EventHandler? UserJoinLeave;
public static void OnUserJoinLeave(EventArgs e)
{
UserJoinLeave?.Invoke(null, e);
}
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? e)
{
RemoveUser(Context.ConnectionId);
OnUserJoinLeave(new EventArgs());
await base.OnDisconnectedAsync(e);
}
public async Task SendToAll(string from, string message)
{
await Clients.All.SendAsync( SendToAllClient, from, message);
}
public static void RemoveUser(string id)
{
ConnectedUsers.Remove(id);
OnUserJoinLeave(null);
}
public static void AddUser(string id, string name)
{
if (!ConnectedUsers.ContainsKey(id))
{
ConnectedUsers.Add(id, name);
OnUserJoinLeave(null);
}
}
}