-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hub.cs
98 lines (91 loc) · 2.85 KB
/
Hub.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Hubs;
namespace DrinkingGame
{
[HubName("BeerHub")]
public class GeneralHub : Hub
{
private static List<string> clients = new List<string>();
private static Dictionary<string, int> glasses = new Dictionary<string, int>();
private static string winnerId = null;
public void Drink()
{
try
{
if (string.IsNullOrEmpty(winnerId))
{
if (clients.Contains(Context.ConnectionId))
{
glasses[Context.ConnectionId]--;
if (glasses[Context.ConnectionId] <= 0)
{
winnerId = Context.ConnectionId;
Clients.Caller.sendMessage("You're the winner");
}
Clients.Clients(clients).broadcastMessage(glasses.Select(Glass.Project));
}
}
}
catch (Exception ex)
{
}
}
public void Reset()
{
try
{
winnerId = null;
foreach (var key in glasses.Keys.ToList())
{
glasses[key] = 100;
}
Clients.Clients(clients).broadcastMessage(glasses.Select(Glass.Project));
}
catch (Exception ex)
{
}
}
public override Task OnConnected()
{
if (!clients.Contains(Context.ConnectionId))
{
clients.Add(Context.ConnectionId);
glasses.Add(Context.ConnectionId, 100);
Clients.Clients(clients).broadcastMessage(glasses.Select(Glass.Project));
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
if (clients.Contains(Context.ConnectionId))
{
clients.Remove(Context.ConnectionId);
glasses.Remove(Context.ConnectionId);
Clients.Clients(clients).broadcastMessage(glasses.Select(Glass.Project));
}
return base.OnDisconnected(stopCalled);
}
}
public class Glass
{
public string Id { get; set; }
public string Email { get; set; }
public int Number { get; set; }
public static Func<KeyValuePair<string, int>, Glass> Project
{
get
{
return e => new Glass
{
Id = e.Key,
Number = e.Value
};
}
}
}
}