-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDedicated.cs
More file actions
394 lines (333 loc) · 13 KB
/
Copy pathDedicated.cs
File metadata and controls
394 lines (333 loc) · 13 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using NLog;
using ZamboniDedicated.Protocol;
using ZamboniDedicated.Protocol.Packets;
using ZamboniDedicated.Protocol.Packets.Signaling;
using ZamboniDedicated.Protocol.Packets.SubPackets;
namespace ZamboniDedicated;
public sealed class Dedicated
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private Thread? _mainThread;
private Thread? _networkThread;
private readonly UdpClient _serverUdpClient;
private readonly Player?[] _players;
private readonly Roster _roster;
private readonly ConcurrentQueue<(IPEndPoint Sender, Packet Packet)> _incomingPacketQueue = new();
public event Action<Dedicated>? Stopped;
private readonly CancellationTokenSource _cts = new();
private readonly Stopwatch _clock = new();
private readonly double _tickPeriodMs;
private double _nextTickDeadlineMs;
private long _ticksRun;
private readonly int _maxClients;
private const int SendConsecutiveEmptyTicksAmount = 4;
private const int ServerShutdownAfterNConsecutiveEmptyTicks = 324000;
private const int KeepaliveMs = 500;
private const int SyncIntervalMs = 200;
private const int StallKickMs = 5000;
private int _consecutiveEmptyTicks;
public Dedicated(int ticksPerSecond, int maxClients, int port)
{
_maxClients = maxClients;
_serverUdpClient = new UdpClient(port);
_players = new Player[_maxClients];
_roster = new Roster();
_tickPeriodMs = 1000.0 / ticksPerSecond;
}
public void Start()
{
_networkThread = new Thread(() => ReceiveLoop(_cts.Token)) { IsBackground = true, Name = "NetworkThread" };
_networkThread.Start();
_mainThread = new Thread(() => MainLoop(_cts.Token)) { IsBackground = true, Name = "MainThread" };
_mainThread.Start();
}
public void Stop()
{
_cts.Cancel();
}
private void MainLoop(CancellationToken cancellationToken)
{
_clock.Start();
_nextTickDeadlineMs = _clock.Elapsed.TotalMilliseconds;
Logger.Info("Server started!");
while (!cancellationToken.IsCancellationRequested)
{
if (_clock.Elapsed.TotalMilliseconds >= _nextTickDeadlineMs)
{
Logger.Trace($"ServerTick: {_ticksRun} Starts");
Tick();
_nextTickDeadlineMs += _tickPeriodMs;
Logger.Trace($"ServerTick: {_ticksRun} Ends");
_ticksRun++;
}
else
{
Thread.Sleep(1);
}
}
Cleanup();
}
private void Tick()
{
ProcessIncomingPackets();
BuildAndSendCombinedInputs();
KeepaliveConnections();
}
private void Cleanup()
{
foreach (var player in _players)
{
if (player == null) continue;
player.ReliableConnection.SendSignalPacket(new DisconnectPacket());
}
_serverUdpClient.Close();
_networkThread?.Join(TimeSpan.FromSeconds(1));
Stopped?.Invoke(this);
Logger.Info("Server stopped");
}
private void ReceiveLoop(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
UdpReceiveResult result;
try
{
result = _serverUdpClient.ReceiveAsync(cancellationToken).AsTask().GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
return;
}
catch (ObjectDisposedException)
{
return;
}
try
{
var packet = PacketDecoder.Decode(result.Buffer);
_incomingPacketQueue.Enqueue((result.RemoteEndPoint, packet));
Logger.Trace($"Received from: {result.RemoteEndPoint.Address} {packet}");
}
catch (Exception ex)
{
Logger.Warn($"Error while parsing packet\n" +
$"From: {result.RemoteEndPoint.Address}\n " +
$"Data: {BitConverter.ToString(result.Buffer)}");
Logger.Warn(ex);
}
}
}
private void ProcessIncomingPackets()
{
int count = _incomingPacketQueue.Count;
for (var i = 0; i < count; i++)
{
try
{
if (!_incomingPacketQueue.TryDequeue(out var tuple))
{
return;
}
var sender = tuple.Sender;
var packet = tuple.Packet;
var player = _players.FirstOrDefault(player => player != null && player.IpEndpoint.Equals(sender));
if (player is not null) player.ReliableConnection.LastReceiveMs = _clock.ElapsedMilliseconds;
if (packet.Header.IsSignalPacket)
{
switch (packet.Header.SignalType)
{
case SignalType.ConnectionRequest:
{
var connectPacket = ConnectPacket.FromHeader(packet.Header);
if (_players.Count(p => p is not null) >= _maxClients)
{
break;
}
if (player is not null)
{
player.ReliableConnection.SendSignalPacket(new ConnectionAcceptPacket(connectPacket.PlayerIdentifier));
break;
}
int slot = Array.IndexOf(_players, null);
var newPlayer = new Player(connectPacket.PlayerIdentifier, sender, _serverUdpClient, _clock);
_players[slot] = newPlayer;
newPlayer.ReliableConnection.SendSignalPacket(new ConnectionAcceptPacket(connectPacket.PlayerIdentifier));
BroadcastRosterUpdate();
Logger.Info($"Player {newPlayer} joined the server");
break;
}
case SignalType.Disconnect:
{
if (player != null)
{
RemovePlayer(player);
Logger.Info($"Player {player} has left the server");
}
break;
}
case SignalType.ResendRequest:
{
if (player is not null)
{
player.ReliableConnection.RetransmitAllUnackedPackets();
}
break;
}
}
continue;
}
if (!packet.Header.IsReliablePacket || player is null)
{
continue;
}
player.ReliableConnection.AcknowledgeUpTo(packet.Header.Acknowledgment);
long now = _clock.ElapsedMilliseconds;
uint missingSeq = 0;
for (int j = packet.SubPackets.Count - 1; j >= 0; j--)
{
var subPacket = packet.SubPackets[j];
uint effectiveSeq = packet.Header.SequenceNumber - (uint)j;
bool isNewPacket = player.ReliableConnection.TryAcceptIncoming(effectiveSeq, out var gap);
missingSeq = gap;
if (!isNewPacket) continue;
if (subPacket.Sync is { } sync)
{
player.ReliableConnection.LastEcho = sync.LocalTimestamp;
player.ReliableConnection.LastEchoReceivedTick = now;
}
switch (subPacket)
{
case SyncSubPacket:
break;
case LobbyMessageSubPacket:
foreach (var peer in _players)
{
if (peer is null) continue;
if (!sender.Equals(peer.IpEndpoint)) peer.ReliableConnection.Send([subPacket]);
}
break;
case ReadinessSubPacket readiness:
{
if (readiness.Ready)
{
player.Ready = true;
bool nowAllReady = AllPlayersReady();
if (nowAllReady)
{
Logger.Info("All players are done loading, the game will start now");
foreach (var peer in _players)
{
if (peer is null) continue;
peer.ReliableConnection.Send([new ReadinessSubPacket(true)]);
}
}
}
break;
}
case PlayerInputSubPacket playerInput:
player.EnqueueInput(playerInput);
break;
}
}
if (missingSeq > 0)
{
player.ReliableConnection.SendSignalPacket(new ResendRequest(missingSeq));
}
if (now - player.ReliableConnection.LastSyncSentMs > SyncIntervalMs)
{
player.ReliableConnection.BuildAndSendSyncPing();
}
}
catch (Exception ex)
{
Logger.Warn("Error while processing packet");
Logger.Warn(ex);
}
}
}
private void BroadcastRosterUpdate()
{
_roster.UpdateRoster(_players);
foreach (var player in _players)
{
if (player is null) continue;
player.ReliableConnection.Send([new RosterUpdateSubPacket(_roster)]);
}
}
private void KeepaliveConnections()
{
var now = _clock.ElapsedMilliseconds;
foreach (var player in _players)
{
if (player is null) continue;
if (now - player.ReliableConnection.LastAnySendMs > KeepaliveMs)
{
player.ReliableConnection.BuildAndSendSyncPing();
}
long silence = now - player.ReliableConnection.LastReceiveMs;
if (player.ReliableConnection.LastReceiveMs != 0 && silence >= StallKickMs)
{
RemovePlayer(player);
Logger.Info($"Player {player} stalled. Kicking from server.");
}
}
}
private void RemovePlayer(Player player)
{
_players[Array.IndexOf(_players, player)] = null;
BroadcastRosterUpdate();
if (!_players.Any(p => p is not null))
{
Stop();
}
}
private bool AllPlayersReady()
{
var allReady = false;
foreach (var player in _players)
{
if (player is null) continue;
if (!player.Ready)
{
allReady = false;
break;
}
allReady = true;
}
return allReady;
}
private void BuildAndSendCombinedInputs()
{
var connected = _players.Where(p => p is not null).Cast<Player>().ToList();
if (connected.Count == 0 || !connected.Any(p => p.HasEverSentInput)) return;
bool anyInputThisTick = connected.Any(p => p.HasPendingInput);
_consecutiveEmptyTicks = anyInputThisTick ? 0 : _consecutiveEmptyTicks + 1;
if (_consecutiveEmptyTicks >= SendConsecutiveEmptyTicksAmount)
{
if (_consecutiveEmptyTicks >= ServerShutdownAfterNConsecutiveEmptyTicks)
{
Stop();
}
return;
}
var inputs = connected.ToDictionary(p => p, p => p.TakeInputForTick());
foreach (var recipient in connected)
{
var others = connected.Where(p => p != recipient).Select(p => inputs[p]).ToList();
if (others.Count == 0) others.Add(new PlayerInputSubPacket(InputPayloadKind.Disconnected, Array.Empty<byte>()));
var combined = new CombinedInputSubPacket
{
RecipientInputsConsumedSinceLastTick = recipient.InputsConsumedSinceLastTick,
RosterVersion = _roster.Version,
PlayerCount = Math.Max(2, connected.Count),
OtherPlayers = others,
};
recipient.ReliableConnection.Send([combined]);
recipient.ResetConsumedCount();
}
}
}