-
Notifications
You must be signed in to change notification settings - Fork 14
/
EchoGameServer.cs
588 lines (495 loc) · 23.6 KB
/
EchoGameServer.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
using Newtonsoft.Json;
using SIT.Coop.Core;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CoopTarkovGameServer
{
public static class ShimExtensionsForNET472
{
public static void Clear<T>(this ConcurrentQueue<T> q)
{
foreach(T item in q)
{
q.Enqueue(item);
}
}
public static void Clear<T>(this ConcurrentBag<T> q)
{
q = new ConcurrentBag<T>();
}
}
public class EchoGameServer : IDisposable
{
/// <summary>
///
/// </summary>
public object UnityPlugin { get; set; }
public delegate void ConnectionReceivedHandler(IPEndPoint endPoint);
public event ConnectionReceivedHandler OnConnectionReceived;
public delegate void ResetServerHandler();
public event ResetServerHandler OnResetServer;
public delegate void LogHandler(string text);
public event LogHandler OnLog;
//public delegate void MethodCallHandler(ConcurrentDictionary<string, int> actionCounts);
//public event MethodCallHandler OnMethodCall;
public static EchoGameServer Instance { get { return Instances.Last(); } }
public static List<EchoGameServer> Instances = new List<EchoGameServer>();
public static int HighestAcceptablePing { get { return 999; } }
public TcpListener tcpServer { get; set; }
public List<UdpClient> udpReceivers;
public int CurrentReceiverIndex = 0;
public int NumberOfReceivers = 2; // Two Channels. Reliable and Unreliable
public int udpReceiverPort { get { return Plugin.UDPPort; } }
public DateTime StartupTime = DateTime.Now;
public bool quit;
public int NumberOfConnections = 0;
public (IPEndPoint, string)? HostConnection;
public readonly ConcurrentDictionary<IPEndPoint, string> ConnectedClients = new ConcurrentDictionary<IPEndPoint, string>();
public readonly ConcurrentDictionary<IPEndPoint, (UdpClient, int)> ConnectedClientToReceiverPort = new ConcurrentDictionary<IPEndPoint, (UdpClient, int)>();
public readonly ConcurrentDictionary<IPEndPoint, DateTime> ConnectedClientsLastTimeDataReceiver = new ConcurrentDictionary<IPEndPoint, DateTime>();
public readonly ConcurrentDictionary<string, IPEndPoint> PlayersToConnectedClients = new ConcurrentDictionary<string, IPEndPoint>();
public readonly ConcurrentDictionary<string, int> MethodCallCounts = new ConcurrentDictionary<string, int>();
public int TotalNumberOfBytesSentLastSecond = 0;
public int TotalNumberOfBytesProcessedLastSecond = 0;
public int TotalNumberOfBytesProcessed = 0;
public readonly TimeSpan ConnectionTimeout = new TimeSpan(0, 2, 0);
public ConcurrentQueue<(IPEndPoint, byte[], string)> EnqueuedDataToSend = new ConcurrentQueue<(IPEndPoint, byte[], string)>();
public ConcurrentQueue<Dictionary<string,object>> DataProcessInsurance = new ConcurrentQueue<Dictionary<string, object>>();
public ConcurrentBag<Dictionary<string, object>> BotSpawnData = new ConcurrentBag<Dictionary<string, object>>();
public ConcurrentBag<Dictionary<string, object>> PlayerSpawnData = new ConcurrentBag<Dictionary<string, object>>();
public ConcurrentQueue<string> Log = new ConcurrentQueue<string>();
public readonly ConcurrentDictionary<IPEndPoint, DateTime> PingTimes = new ConcurrentDictionary<IPEndPoint, DateTime>();
public readonly ConcurrentDictionary<IPEndPoint, DateTime> PongTimes = new ConcurrentDictionary<IPEndPoint, DateTime>();
public readonly ConcurrentBag<(string, string, long)> ProcessedEvents = new ConcurrentBag<(string, string, long)>();
public DateTime? GameServerClock { get; private set; }
public Guid InstanceId { get; private set; }
public readonly List<TcpClient> ConnectedClientsTcp = new List<TcpClient>();
public EchoGameServer()
{
InstanceId = Guid.NewGuid();
//if (startingUdpPort.HasValue) udpReceiverPort = startingUdpPort.Value;
// Only handle 1 instance for now
Instances.Clear();
Instances.Add(this);
}
public void CreateListenersAndStart()
{
//tcpReceiver = new TcpClient();
udpReceivers = new List<UdpClient>();
for (var i = 0; i < NumberOfReceivers; i++)
{
var newPort = udpReceiverPort + i;
//if (UPnP.NAT.Discover())
//{
// UPnP.NAT.ForwardPort(newPort, ProtocolType.Udp, "SIT-Tarkov-" + i);
//}
//var udpReceiver = new UdpClient(newPort);
var newIpEndPoint = new IPEndPoint(IPAddress.Any, newPort);
var udpReceiver = new UdpClient(newIpEndPoint);
AddToLog(this.GetType() + ": Started udp receiver " + newIpEndPoint.ToString());
//udpReceiver.AllowNatTraversal(true);
//udpReceiver.DontFragment = true;
//udpReceiver.DontFragment = false;
udpReceiver.Client.SendTimeout = 500; // defaulted min
udpReceiver.Client.ReceiveTimeout = 500; // defaulted min
//const int SIO_UDP_CONNRESET = -1744830452;
//udpReceiver.Client.IOControl(
// (IOControlCode)SIO_UDP_CONNRESET,
// new byte[] { 0, 0, 0, 0 },
// null
//);
//udpReceiver.Client.ReceiveBufferSize = 50;
//udpReceiver.Client.SendBufferSize = 300;
udpReceiver.Client.ReceiveBufferSize = 16384;
udpReceiver.Client.SendBufferSize = 16384;
udpReceiver.BeginReceive(UdpReceive, udpReceiver);
udpReceivers.Add(udpReceiver);
}
// tcpServer = new TcpListener(new IPEndPoint(IPAddress.Any, 7076));
// tcpServer.Server.ReceiveBufferSize = 2048;
// tcpServer.Server.ReceiveTimeout = HighestAcceptablePing;
// tcpServer.Server.SendTimeout = HighestAcceptablePing;
//StartTcpServerAndAccept();
UpdatePings();
ServerSendOutEnqueuedData();
}
//public void StartTcpServerAndAccept()
//{
// tcpServer.Start();
// AddToLog(this.GetType() + ": Started tcp receiver on " + tcpServer.LocalEndpoint);
// tcpServer.BeginAcceptTcpClient((IAsyncResult result) =>
// {
// StartTcpServerAndAccept();
// TcpClient client = tcpServer.EndAcceptTcpClient(result); //creates the TcpClient
// NetworkStream ns = client.GetStream();
// ConnectedClientsTcp.Add(client);
// while (client.Connected) //while the client is connected, we look for incoming messages
// {
// try
// {
// byte[] msg = new byte[2048]; //the messages arrive as byte array
// ns.Read(msg, 0, msg.Length); //the same networkstream reads the message sent by the client
// Debug.WriteLine("TCP:" + Encoding.Default.GetString(msg));
// AddToLog("TCP:" + Encoding.Default.GetString(msg));
// foreach(var cc in ConnectedClientsTcp)
// {
// NetworkStream ccns = cc.GetStream();
// if(ccns != null && ccns.CanWrite)
// {
// ccns.Write(msg, 0, msg.Length);
// }
// }
// client.Close();
// //ns.Write(msg, 0, msg.Length);
// }
// catch (Exception)
// {
// }
// }
// ConnectedClientsTcp.Remove(client);
// }, tcpServer); //this is called asynchronously and will run in a different thread
//}
public void UdpReceive(IAsyncResult ar)
{
var udpClient = ar.AsyncState as UdpClient;
IPEndPoint endPoint = null;
var data = udpClient.EndReceive(ar, ref endPoint);
ServerHandleReceivedData(data, endPoint);
udpClient.BeginReceive(UdpReceive, udpClient);
}
//public void TcpHandler(IAsyncResult ar)
//{
// var tcpListener = ar.AsyncState as TcpListener;
// var socket = tcpListener.EndAcceptSocket(ar);
// socket.()
// using (Stream myStream = new NetworkStream(socket))
// {
// StreamReader reader = new StreamReader(myStream);
// StreamWriter writer = new StreamWriter(myStream)
// { AutoFlush = true };
// ServerHandleReceivedDataTcp(ref reader, ref writer, (IPEndPoint)socket.RemoteEndPoint);
// }
// TcpHandler(ar);
//}
public void ResetServer()
{
StartupTime = DateTime.Now;
ConnectedClientToReceiverPort.Clear();
ConnectedClients.Clear();
ConnectedClientsLastTimeDataReceiver.Clear();
PlayersToConnectedClients.Clear();
MethodCallCounts.Clear();
DataProcessInsurance.Clear();
EnqueuedDataToSend.Clear();
BotSpawnData.Clear();
PlayerSpawnData.Clear();
Log = new ConcurrentQueue<string>();
TotalNumberOfBytesSentLastSecond = 0;
TotalNumberOfBytesProcessedLastSecond = 0;
TotalNumberOfBytesProcessed = 0;
if(OnResetServer != null)
{
OnResetServer();
}
}
public async void UpdatePings()
{
await Task.Delay(50);
var array = ASCIIEncoding.ASCII.GetBytes("Ping");
foreach (IPEndPoint item in ConnectedClients.Keys)
{
PingTimes.TryRemove(item, out _);
udpReceivers[0].Send(array, array.Length, item);
//EnqueuedDataToSend.Enqueue((item, array, null));
PingTimes.TryAdd(item, DateTime.Now);
}
UpdatePings();
}
private async void ServerSendOutEnqueuedData()
{
try
{
//if (DataProcessInsurance.Any())
//{
// var bytes = ASCIIEncoding.ASCII.GetBytes(JsonConvert.SerializeObject(DataProcessInsurance));
// EnqueuedDataToSend.Enqueue((null, bytes, null));
//}
//while (EnqueuedDataToSend.Any())
if (EnqueuedDataToSend.Any())
{
if(EnqueuedDataToSend.TryDequeue(out (IPEndPoint, byte[], string) result))
{
foreach (IPEndPoint item in ConnectedClients.Keys)
{
//await udpReceivers[0].SendAsync(queuedData, queuedData.Length, item);
udpReceivers[0].Send(result.Item2, result.Item2.Length, item);
}
}
//var queuedData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(EnqueuedDataToSend.Select(x => Encoding.UTF8.GetString(x.Item2))));
//foreach (IPEndPoint item in ConnectedClients.Keys)
//{
// //await udpReceivers[0].SendAsync(queuedData, queuedData.Length, item);
// udpReceivers[0].Send(queuedData, queuedData.Length, item);
//}
//EnqueuedDataToSend.Clear();
}
}
catch (Exception ex)
{
AddToLog(this.GetType() + ex.ToString());
}
await Task.Delay(1);
ServerSendOutEnqueuedData();
}
private void ServerHandleReceivedDataTcp(ref StreamReader reader, ref StreamWriter writer, IPEndPoint receivedIpEndPoint)
{
if (reader == null)
return;
try
{
var allText = reader.ReadToEnd();
if (string.IsNullOrEmpty(allText))
return;
if (allText.Length == 4 && allText == "Pong")
{
PongTimes.TryRemove(receivedIpEndPoint, out _);
PongTimes.TryAdd(receivedIpEndPoint, DateTime.Now);
writer.Write("Ping");
writer.Flush();
return;
}
if (allText == "GET_PLAYERS")
{
if (DataProcessInsurance.Any())
{
var queuedData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(EnqueuedDataToSend.Select(x => Encoding.UTF8.GetString(x.Item2))));
}
}
if (allText == "CHECK_DEAD")
{
writer.Write("A COUPLE OF GUYS ARE DEAD LIKE");
if (DataProcessInsurance.Any())
{
var queuedData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(DataProcessInsurance.Select(x=>x)));
writer.Write(queuedData);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private void ServerHandleReceivedData(byte[] array, IPEndPoint receivedIpEndPoint)
{
string @string = Encoding.ASCII.GetString(array);
if (@string.Length > 0)
{
try
{
if (@string.Length == 4 && @string == "Pong")
{
PongTimes.TryRemove(receivedIpEndPoint, out _);
PongTimes.TryAdd(receivedIpEndPoint, DateTime.Now);
EnqueuedDataToSend.Enqueue((receivedIpEndPoint, Encoding.ASCII.GetBytes("Ping"), null));
//udpClient.BeginReceive(DataReceivedServer, udpClient);
return;
}
// If the "Server" player is saying "Start" then its a new game and clean up!
if (@string.StartsWith("Start="))
{
var accountId = @string.Split('=')[1];
PongTimes.TryRemove(receivedIpEndPoint, out _);
PongTimes.TryAdd(receivedIpEndPoint, DateTime.Now);
PingTimes.TryRemove(receivedIpEndPoint, out _);
PingTimes.TryAdd(receivedIpEndPoint, DateTime.Now);
ResetServer();
AddNewConnection(receivedIpEndPoint, accountId);
//udpClient.BeginReceive(DataReceivedServer, udpClient);
return;
}
if (@string.StartsWith("Connect="))
{
var accountId = @string.Split('=')[1];
PongTimes.TryRemove(receivedIpEndPoint, out _);
PongTimes.TryAdd(receivedIpEndPoint, DateTime.Now);
PingTimes.TryRemove(receivedIpEndPoint, out _);
PingTimes.TryAdd(receivedIpEndPoint, DateTime.Now);
AddNewConnection(receivedIpEndPoint, accountId);
//udpClient.BeginReceive(DataReceivedServer, udpClient);
return;
}
if (udpReceivers.Count == 0)
{
AddToLog("There are no udpReceivers!!!");
return;
}
AddNewConnection(receivedIpEndPoint, null);
if (ConnectedClients.Count == 0)
{
AddToLog("There are no ConnectedClients!!!");
return;
}
foreach (var client in ConnectedClients.Keys)
{
foreach (var udpServer in udpReceivers)
{
//_ = udpServer.SendAsync(array, array.Length, client);
udpServer.Send(array, array.Length, client);
//udp.BeginSend(array, array.Length, (IAsyncResult r) => { }, client);
}
}
//EnqueuedDataToSend.Enqueue((receivedIpEndPoint, array, null));
/*
var dictData = JsonConvert.DeserializeObject<Dictionary<string, object>>(@string);
if (dictData != null)
{
//if (!dictData.ContainsKey("accountId"))
//{
// //AddToLog("Thrown unusable Dictionary: Missing accountId!");
// return;
//}
if (dictData.ContainsKey("method") || dictData.ContainsKey("m"))
{
if (!dictData.ContainsKey("method"))
dictData.Add("method", dictData["m"]);
var method = dictData["method"].ToString();
if (!string.IsNullOrEmpty(method))
{
if (!MethodCallCounts.ContainsKey(method))
{
MethodCallCounts.TryAdd(method, 0);
}
if (MethodCallCounts.TryGetValue(method, out int callCount))
{
callCount++;
MethodCallCounts[method] = callCount;
}
if (OnMethodCall != null)
{
OnMethodCall(MethodCallCounts);
}
//if (method == "Damage"
// || method == "Dead"
// //|| method == "Move"
// )
//{
// foreach (var client in ConnectedClients.Keys)
// {
// udpReceivers[0].Send(array, array.Length, client);
// udpReceivers[1].Send(array, array.Length, client);
// }
// AddToLog($"Received {method} to {dictData["accountId"]}");
// return;
//}
// Always push Dead calls !
//if (method == "Dead" || method == "Damage")
//{
// DataProcessInsurance.Enqueue(dictData);
//}
}
//string accountId = dictData["accountId"].ToString();
//if (dictData.ContainsKey("tick"))
//{
// long ticks = long.Parse(dictData["tick"].ToString());
// if (!ProcessedEvents.Any(x => x.Item1 == method && x.Item2 == accountId && x.Item3 == ticks))
// EnqueuedDataToSend.Enqueue((receivedIpEndPoint, array, accountId));
// ProcessedEvents.Add((method, accountId, ticks));
//}
//else
//{
//}
//foreach (var client in ConnectedClients.Keys)
//{
// udpReceivers[0].Send(array, array.Length, client);
// udpReceivers[1].Send(array, array.Length, client);
//}
}
}
*/
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
/// <summary>
/// Send parity data to ALL clients
/// </summary>
//private async void SendParityData()
//{
// AddToLog($"Sending out Spawn Data, {PlayerSpawnData.Count} Players, {BotSpawnData.Count} Bots");
// foreach (var bpd in BotSpawnData)
// {
// EnqueuedDataToSend.Enqueue((null, Encoding.Default.GetBytes(JsonConvert.SerializeObject(bpd))));
// await Task.Delay(1000); // Delay by 1 second to ensure data is actually sent
// }
// foreach (var bpd in PlayerSpawnData)
// {
// EnqueuedDataToSend.Enqueue((null, Encoding.Default.GetBytes(JsonConvert.SerializeObject(bpd))));
// await Task.Delay(1000); // Delay by 1 second to ensure data is actually sent
// }
//}
private void AddNewConnection(IPEndPoint receivedIpEndPoint, string playerId, bool isHost = false)
{
if (receivedIpEndPoint == null)
{
AddToLog("IP End Point is NULL! WTF!");
return;
}
if (udpReceivers.Count == 0)
{
AddToLog("AddNewConnection attempting to add new connection when there are no receivers!");
return;
}
if (!ConnectedClients.Keys.Any((IPEndPoint x) => x.ToString() == receivedIpEndPoint.ToString()))
{
ConnectedClientToReceiverPort.TryAdd(receivedIpEndPoint, (udpReceivers[0], udpReceiverPort + 0));
NumberOfConnections++;
// continuously attempt to add
ConnectedClients.TryAdd(receivedIpEndPoint, playerId);
if (isHost)
HostConnection = (receivedIpEndPoint, playerId);
//Debug.WriteLine(this.GetType() + ": DataReceivedServer::New Connection from " + receivedIpEndPoint.ToString());
//Console.WriteLine(this.GetType() + ": DataReceivedServer::New Connection from " + receivedIpEndPoint.ToString());
if(OnConnectionReceived != null)
{
OnConnectionReceived(receivedIpEndPoint);
}
AddToLog(this.GetType() + ": DataReceivedServer::New Connection from " + receivedIpEndPoint.ToString());
}
}
public void AddToLog(string text)
{
//Debug.WriteLine(text);
if(OnLog != null)
{
OnLog(text);
}
}
//~EchoGameServer()
//{
//}
public void Dispose()
{
// foreach (var c in udpReceivers)
// {
// c.Close();
// c.Dispose();
// }
// udpReceivers.Clear();
// Instances.Clear();
// ResetServer();
}
}
}