-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameCoordinator.cs
More file actions
95 lines (79 loc) · 2.14 KB
/
GameCoordinator.cs
File metadata and controls
95 lines (79 loc) · 2.14 KB
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
public interface IGameCoordinator
{
public void EnqueueClient(MessageClient messageClient);
public void Start();
public void Stop();
}
public class GameCoordinator : IGameCoordinator
{
private BlockingCollection<MessageClient> _newClients = new();
private Dictionary<int, Game> _games = new();
private bool _running = true;
private Thread _thread;
private CancellationTokenSource _cancelSource = new();
public GameCoordinator()
{
// TEST CODE
_games.Add(1, new Game() { Id = 1 });
_thread = new(() => this.Run());
}
public void EnqueueClient(MessageClient messageClient)
{
_newClients.Add(messageClient);
}
public void Start()
{
_thread.Start();
}
public void Stop()
{
_running = false;
_cancelSource.Cancel();
_thread.Join();
}
private void Run()
{
while (_running)
{
try
{
if (!_cancelSource.IsCancellationRequested
&& _newClients.TryTake(out MessageClient? mc, System.Threading.Timeout.Infinite, _cancelSource.Token))
{
ValidateClient(mc);
}
}
catch (System.Net.Sockets.SocketException sex)
{
Console.WriteLine($"Socket Error: {sex}");
}
catch (System.OperationCanceledException)
{
Console.WriteLine($"GameCoordinator.Run Cancelled");
}
}
}
private async void ValidateClient(MessageClient mc)
{
try
{
var m = await mc.Receive();
if (m.type == (Int16)MessageTypes.ConnectionRequest)
{
ConnectionRequest r = Serializer.Deserialize<ConnectionRequest>(m.data);
Console.WriteLine($"{r.User} {r.Game}");
}
else
{
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}