-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
430 lines (390 loc) · 16.2 KB
/
Program.cs
File metadata and controls
430 lines (390 loc) · 16.2 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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
namespace MovementSystemServer
{
public class Position
{
public float x { get; set; }
public float y { get; set; }
public float z { get; set; }
}
public class Rotation
{
public float x { get; set;}
public float y { get; set;}
public float z { get; set;}
public float w { get; set;}
}
public class PlayerInfo
{
public int puppetID { get; set; } = -1;
public string playerName { get; set; }
public Position position { get; set; }
public Rotation rotation { get; set; }
public int health { get; set; }
}
public class ServerPlayer
{
public PlayerInfo info { get; set; }
public TcpClient tcpClient { get; set; }
public Thread thread { get; set; }
}
public class ObjectInfo
{
public int puppetID { get; set; } = -1;
public Position position { get; set; }
public Rotation rotation { get; set; }
public int master { get; set; } = -1;
}
[Serializable]
public class ServerInfo
{
public string type = "ServerInfo";
public PlayerInfo master { get; set; }
}
[Serializable]
public class PlayerInfoList
{
public string type = "PlayerInfo";
public List<PlayerInfo> players = new List<PlayerInfo>();
}
[Serializable]
public class ObjectInfoList
{
public string type = "ObjectInfo";
public List<ObjectInfo> objects = new List<ObjectInfo>();
}
public class TypeCheck { public string type; }
public class Program
{
private const int maxPlayers = 4;
public TcpListener server;
public static List<ServerPlayer> serverPlayers = new List<ServerPlayer>();
public static List<PlayerInfo> players = new List<PlayerInfo>();
public static List<TcpClient> clients = new List<TcpClient>();
public static List<ObjectInfo> objects = new List<ObjectInfo>();
public static int expectedKB = 4;
//public static PlayerInfo master;
public static ServerInfo serverInfo = new ServerInfo();
public static void Main(string[] args)
{
Program program = new();
ConsoleHandler ch = new() { program = program };
Thread serverThread = new Thread(program.StartServer) { IsBackground = true, Priority = ThreadPriority.Highest };
//serverThread.Start();
Thread consoleThread = new Thread(ch.StartConsole) { IsBackground = true };
consoleThread.Start();
//Thread broadcast = new Thread(program.BroadcastPuppetData) { IsBackground = true };
//broadcast.Start();
// while (serverThread.IsAlive) { Thread.Sleep(100); }
serverInfo.master = new PlayerInfo();
program.StartServer();
}
public void StartServer()
{
try
{
IPAddress address = IPAddress.Any;
int port = 37484;
server = new TcpListener(address, port);
server.Start();
Logger.Log($"Listening on {address}");
Logger.Log($"Listening on {port}");
Console.WriteLine("Server started. Waiting for connections...");
while (true)
{
TcpClient client = server.AcceptTcpClient();
IPEndPoint endPoint = client.Client.RemoteEndPoint as IPEndPoint;
Console.WriteLine($"Client {endPoint.Address}:{endPoint.Port} connected!");
lock (clients)
{
if (clients.Count < maxPlayers) { clients.Add(client); }
else { Logger.LogWarning($"Client {endPoint.Address}:{endPoint.Port} exceeded max players"); MaxPlayer(client); continue; }
}
Thread clientThread = new Thread(() => HandleClient(client))
{
IsBackground = true
};
clientThread.Start();
}
}
catch (Exception e)
{
Logger.LogError($"Error: {e.Message}");
}
finally
{
server.Stop();
Logger.Log("Server stopped.");
}
}
private static PlayerInfo CheckMaster()
{
try { if (serverInfo.master.puppetID == -1) { PlayerInfo p = players.First(); Logger.Log($"{p.playerName} has been selected as master"); return p; } } catch { return new PlayerInfo(); }
return serverInfo.master;
}
private bool ClientCode(string message, TcpClient client, PlayerInfo player)
{
switch (message)
{
case "Disconnect":
Disconnect(client, player.puppetID);
return true;
default:
return false;
}
}
private void HandleClient(TcpClient client)
{
int puppetID = AssignPuppetID();
try
{
NetworkStream stream = client.GetStream();
byte[] bytes = new byte[1024 * expectedKB];
string data = null;
byte[] puppetIDData = Encoding.UTF8.GetBytes($"{puppetID}\n");
stream.Write(puppetIDData, 0, puppetIDData.Length);
Console.WriteLine($"Assigned Puppet ID: {puppetID}");
Thread.Sleep(100);
while (client.Connected)
{
stream.ReadTimeout = 5000;
int bytesRead = stream.Read(bytes, 0, bytes.Length);
//Logger.Log(bytesRead.ToString());
if (bytesRead == 0) break;
data = Encoding.UTF8.GetString(bytes, 0, bytesRead);
string[] datas = data.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
try
{
foreach (string d in datas)
{
Logger.LogWarning(d);
TypeCheck tp = JsonConvert.DeserializeObject<TypeCheck>(d);
if (ClientCode(d, client, FindPlayerByID(puppetID))) { return; }
//ReceiveCommand(d,client);
//ReceivePlayerData(d, client,puppetID);
try { ReceivePlayerData(d, client, puppetID); continue; } catch (IncompatiblePacketException e) { } catch (Exception e) { Logger.LogError(e.ToString()); }
try { ReceiveCommand(d, client); continue; } catch (IncompatiblePacketException e) { } catch (Exception e) { Logger.LogError(e.ToString()); }
try { ReceiveObjectData(d, client); continue; } catch (IncompatiblePacketException e) { } catch (Exception e) { Logger.LogError(e.ToString()); }
//try { Thread commandThread = new Thread(() => ReceiveCommand(d, client)) { IsBackground = true }; commandThread.Start(); continue; } catch { }
}
}
catch (JsonSerializationException e)
{
Logger.LogError($"Packet error: {e.Message}");
continue;
}
catch (JsonReaderException e)
{
Logger.LogError($"Packet error: {e.Message}");
continue;
}
catch (Exception e)
{
Logger.LogError(e.Message);
}
try { BroadcastPlayerData(); BroadcastObjectData(); }
catch (Exception e) { Logger.LogError(e.Message); continue; };
}
}
catch (Exception e)
{
Logger.LogError($"Client connection error: {e}");
if (e.Message.Contains("A connection attempt failed because the connected party did not properly respond after a period of time"))
{
Logger.LogError("Read failure");
byte[] data = Encoding.UTF8.GetBytes("Read failure");
NetworkStream stream = client.GetStream();
stream.WriteTimeout = 500;
stream.Write(data, 0, data.Length);
}
Disconnect(client, puppetID);
}
}
void ReceiveCommand(string data, TcpClient client)
{
Command command = JsonConvert.DeserializeObject<Command>(data);
if (command.command == null) throw new IncompatiblePacketException("Incompatible packet for commands");
switch (command.command)
{
case "RequestID":
CommandHandler.AssignObjectID(command,client);
break;
default:
throw new IncompatiblePacketException("No proper command found");
}
}
void ReceivePlayerData(string data, TcpClient client, int puppetID)
{
PlayerInfo playerInfo = JsonConvert.DeserializeObject<PlayerInfo>(data);
playerInfo.puppetID = puppetID; // Assign puppetID
if (playerInfo.playerName == null) throw new IncompatiblePacketException("Incompatible packet for Player Data");
lock (players)
{
playerInfo.playerName = NameCheck(playerInfo);
IPEndPoint ip = client.Client.RemoteEndPoint as IPEndPoint;
//playerInfo.IPv4 = ip.Address.ToString();
// Find existing player with the same puppetID and update their info, or add new player
PlayerInfo existingPlayer = FindPlayerByID(puppetID);
if (existingPlayer != null)
{
// Update existing player's data
existingPlayer.playerName = playerInfo.playerName;
existingPlayer.position = playerInfo.position;
existingPlayer.health = playerInfo.health;
}
else
{
// Add new player if not found
players.Add(playerInfo);
lock (serverPlayers) { ServerPlayer sp = new ServerPlayer { info = playerInfo, tcpClient = client, thread = Thread.CurrentThread }; serverPlayers.Add(sp); }
lock (serverInfo.master) { serverInfo.master = CheckMaster(); }
CommandHandler.BroadcastMaster(serverInfo.master);
}
}
}
void ReceiveObjectData(string data, TcpClient client)
{
ObjectInfo objectInfo = JsonConvert.DeserializeObject<ObjectInfo>(data);
if (objectInfo.master == null) throw new IncompatiblePacketException("Incompatible packet for ObjectData");
ObjectInfo existingObj = FindObjectByID(objectInfo.puppetID);
if (existingObj != null)
{
existingObj.position = objectInfo.position;
}
else
{
//objectInfo.puppetID = AssingPuppetID();
objects.Add(objectInfo);
}
}
string NameCheck(PlayerInfo playerInfo)
{
if (playerInfo.playerName == "") { return $"Puppet{playerInfo.puppetID}"; }
return playerInfo.playerName;
}
public static void Disconnect(TcpClient client, int puppetID)
{
lock (clients)
{
clients.Remove(client);
}
ServerPlayer sp = FindServerPlayer(FindPlayerByID(puppetID));
lock (players)
{
serverPlayers.Remove(sp);
players.Remove(FindPlayerByID(puppetID));
if (serverInfo.master.puppetID == puppetID) { Logger.LogWarning($"Master disconnected, attempting to assign new Master"); serverInfo.master = new(); serverInfo.master = CheckMaster(); }
}
client.Close();
Logger.Log($"Client with Puppet ID {puppetID} disconnected.");
Thread.CurrentThread.Join();
}
public static void Disconnect(TcpClient client)
{
lock (clients)
{
clients.Remove(client);
}
Logger.Log($"Client {client.Client.RemoteEndPoint} disconnected.");
client.Close();
}
public static PlayerInfo FindPlayerByID(int playerID)
{
foreach (PlayerInfo player in players) { if (player.puppetID == playerID) { return player; } }
return null;
}
public static ObjectInfo FindObjectByID(int objectID)
{
if (objectID == -1) { return null; }
foreach (ObjectInfo obj in objects) { if (obj.puppetID == objectID) { return obj; } }
return null;
}
public static ServerPlayer FindServerPlayer(PlayerInfo pinfo)
{
if (pinfo == null) { return null; }
foreach (ServerPlayer sps in serverPlayers) { if (sps.info.puppetID == pinfo.puppetID) { return sps; } }
return null;
}
public static ServerPlayer FindServerPlayer(TcpClient client)
{
foreach (ServerPlayer sps in serverPlayers) { if (sps.tcpClient.Client.RemoteEndPoint == client.Client.RemoteEndPoint) { return sps; } }
return null;
}
public static int AssignPuppetID()
{
int id;
Random random = new Random();
do { id = random.Next(1, 99); } while (players.Contains(FindPlayerByID(id))||objects.Contains(FindObjectByID(id)));
return id;
}
public void BroadcastServerInfo()
{
string s = JsonConvert.SerializeObject(serverInfo);
Logger.LogWarning(s);
byte[] data = Encoding.UTF8.GetBytes(s + '\n');
BroadcastData(data);
}
private void BroadcastPlayerData()
{
// Create PlayerInfoList from the players dictionary
PlayerInfoList puppetInfoList = new PlayerInfoList
{
players = players
};
// Serialize PlayerInfoList and send to each connected client
string allPuppetData = JsonConvert.SerializeObject(puppetInfoList);
byte[] data = Encoding.UTF8.GetBytes(allPuppetData + '\n');
BroadcastData(data);
}
private void BroadcastObjectData()
{
ObjectInfoList objectInfoList = new ObjectInfoList
{
objects = objects
};
string allPuppetData = JsonConvert.SerializeObject(objectInfoList);
byte[] data = Encoding.UTF8.GetBytes(allPuppetData + '\n');
BroadcastData(data);
}
public static void BroadcastData(byte[] data)
{
lock (clients)
{
foreach (TcpClient client in clients)
{
try
{
NetworkStream stream = client.GetStream();
if (true)
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
catch (InvalidOperationException e)
{
Logger.LogError($"{e}");
Disconnect(client);
continue;
}
catch (Exception e) { Logger.LogError($"{e}"); continue; }
}
}
}
private void MaxPlayer(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] data = Encoding.UTF8.GetBytes("Server full");
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
}
}