-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
SocketHandler.cs
440 lines (362 loc) · 15.2 KB
/
SocketHandler.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
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using vtortola.WebSockets;
/*
LiveMap - A LiveMap for FiveM servers
Copyright (C) 2017 Jordan Dalton
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the file "LICENSE". If not, see <http://www.gnu.org/licenses/>.
*/
namespace Havoc.Live_Map
{
class SocketHandler
{
WebSocketServer server;
JObject playerData;
ConcurrentDictionary<string, WebSocket> clients = new ConcurrentDictionary<string, WebSocket>();
ConcurrentQueue<JObject> sendQueue = new ConcurrentQueue<JObject>();
public SocketHandler(WebSocketServer server)
{
this.server = server;
playerData = new JObject();
server.OnConnect += Server_OnConnect;
server.OnDisconnect += Server_OnDisconnect;
server.OnError += Server_OnError;
server.OnMessage += Server_OnMessage;
}
private void Server_OnMessage(WebSocket ws, string msg)
{
string[] args = msg.Split(' ');
LiveMap.Log(LiveMap.LogLevel.Basic, "Recieved message from client {0}:\n\t\"{1}\"", ws.RemoteEndpoint.ToString(), msg);
}
private void Server_OnError(WebSocket ws, Exception ex)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Socket error from {0}: {1}", ws == null ? "Unknown" : ws.RemoteEndpoint.ToString(), ex.Message);
if (ws != null)
{
WebSocket destory;
if (clients.TryRemove(ws.RemoteEndpoint.ToString(), out destory))
{
destory.Dispose();
LiveMap.Log(LiveMap.LogLevel.Basic, "Removed {0} socket because of an error: {1}\nInner: {2}", ws.RemoteEndpoint.ToString(), ex.Message, ex.InnerException);
}
else
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Couldn't remove {0} from the clients dic.", ws.RemoteEndpoint.ToString());
}
}
}
private void Server_OnDisconnect(WebSocket ws)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Socket connection was closed at {0}", ws.RemoteEndpoint.ToString());
WebSocket destory;
if (clients.TryRemove(ws.RemoteEndpoint.ToString(), out destory))
{
destory.Dispose();
LiveMap.Log(LiveMap.LogLevel.Basic, "Removed {0} socket because it disconnected", ws.RemoteEndpoint.ToString());
}
else
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Couldn't remove {0} from the clients dic.", ws.RemoteEndpoint.ToString());
}
}
private void Server_OnConnect(WebSocket ws)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Socket connection opened at {0}", ws.RemoteEndpoint.ToString());
if (clients.TryAdd(ws.RemoteEndpoint.ToString(), ws))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Added client {0} to the client dictionary", ws.RemoteEndpoint.ToString());
}
else
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Couldn't add {0} to the client dic", ws.RemoteEndpoint.ToString());
}
}
private void MakeSurePlayerExists(string identifier)
{
lock (playerData)
{
if (playerData[identifier] == null)
{
playerData[identifier] = new JObject();
}
}
}
public async Task SendWebsocketData()
{
while (true)
{
// Only send the data every .5 seconds
await Task.Delay(TimeSpan.FromMilliseconds(LiveMap.waitSeconds)).ConfigureAwait(false);
//LiveMap.Log(LiveMap.LogLevel.All, "Checking send queue");
List<string> disconnectedClients = new List<string>();
if (sendQueue.Count != 0)
{
JObject payload;
if (sendQueue.TryDequeue(out payload))
{
foreach (KeyValuePair<string, WebSocket> pair in clients)
{
string endpoint = pair.Key;
WebSocket ws = pair.Value;
if (!ws.IsConnected)
{
disconnectedClients.Add(endpoint);
continue;
}
LiveMap.Log(LiveMap.LogLevel.All, "Sending payload of \"{0}\" to {1}", payload["type"], endpoint);
await ws.WriteStringAsync(payload.ToString(Newtonsoft.Json.Formatting.None), CancellationToken.None).ConfigureAwait(false);
}
}
else
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Couldn't get the latest payload to send.");
}
}
else
{
// No payload in the queue, may as well send player data
// Generate the payload
JObject payload = new JObject();
JArray playerDataArray = new JArray();
lock (playerData)
{
foreach (KeyValuePair<string, JToken> data in playerData)
{
playerDataArray.Add(data.Value);
}
}
if (playerDataArray.Count == 0)
{
//LiveMap.Log(LiveMap.LogLevel.All, "playerDataArray.Count is 0");
continue;
}
payload["type"] = "playerData";
payload["payload"] = playerDataArray;
foreach (KeyValuePair<string, WebSocket> pair in clients)
{
string endpoint = pair.Key;
WebSocket ws = pair.Value;
if (!ws.IsConnected)
{
disconnectedClients.Add(endpoint);
continue;
}
//LiveMap.Log(LiveMap.LogLevel.All, "Sending payload of \"{0}\" to {1}", payload["type"], endpoint);
await ws.WriteStringAsync(payload.ToString(Newtonsoft.Json.Formatting.None), CancellationToken.None).ConfigureAwait(false);
}
} // end of payload sending.. Time to disconnect clients that are no longer connected
//LiveMap.Log(LiveMap.LogLevel.All, "Client size: {0}", clients.Count);
foreach(string endpoint in disconnectedClients)
{
WebSocket des;
if(clients.TryRemove(endpoint, out des))
{
LiveMap.Log(LiveMap.LogLevel.All, "Garbage cleanup.. Removed disconnected client {0}", endpoint);
des.Dispose();
}
}
}
}
private void PlayerHadBeenUpdated(string identifier, JToken playerData)
{
JObject payload = new JObject();
payload["type"] = "playerData";
JArray arr = new JArray();
arr.Add(playerData);
payload["payload"] = arr;
sendQueue.Enqueue(payload);
}
public void AddPlayerData(string identifier, string key, object data)
{
LiveMap.Log(LiveMap.LogLevel.All, "Adding player {0}'s \"{1}\"", identifier, key);
MakeSurePlayerExists(identifier);
if (string.IsNullOrEmpty(identifier))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Identifier is null or empty");
return;
}
if (string.IsNullOrEmpty(key))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot add key to player ({0}) because it's null or empty", identifier);
return;
}
if (data == null)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot add \"{1}\" to player ({0}) because it's null.", identifier, key);
return;
}
lock (playerData)
{
JObject playerObj = (JObject)playerData[identifier];
if(playerObj[key] == null)
playerObj.Add(key, JToken.FromObject(data));
//PlayerHadBeenUpdated(identifier, playerObj);
}
LiveMap.Log(LiveMap.LogLevel.Basic, "Added \"{1}\" to player {0} with value of \"{2}\"", identifier, key, data);
}
public void UpdatePlayerData(string identifier, string key, object newData)
{
LiveMap.Log(LiveMap.LogLevel.All, "Updating player {0}'s \"{1}\"", identifier, key);
MakeSurePlayerExists(identifier);
if (string.IsNullOrEmpty(identifier))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Identifier is null or empty. Cannot update player data");
return;
}
if (string.IsNullOrEmpty(key))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot update player ({0}) because key is null or empty", identifier);
return;
}
// Check if `data` is null
if (newData == null)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot update \"{0}\" for {1} because it's null", key, identifier);
return;
}
lock (playerData)
{
JObject playerObj = (JObject)playerData[identifier];
playerObj[key] = JToken.FromObject(newData);
playerData[identifier] = playerObj;
//PlayerHadBeenUpdated(identifier, playerObj);
}
LiveMap.Log(LiveMap.LogLevel.All, "Updated player {0}'s \"{1}\" to \"{2}\"", identifier, key, newData);
}
public void RemovePlayerData(string identifier, string key)
{
if (string.IsNullOrEmpty(identifier))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Identifier is null or empty.. Cannot remove player data");
return;
}
if (string.IsNullOrEmpty(key))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot remove data from player ({0}) because key is null or empty", identifier);
return;
}
MakeSurePlayerExists(identifier);
lock (playerData)
{
JObject playerObj = (JObject)playerData[identifier];
if (playerObj[key] != null)
{
if (playerObj.Remove(key))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Removed \"{0}\" from player {1}", key, identifier);
//PlayerHadBeenUpdated(identifier, playerObj);
}
else
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Couldn't remove \"{0}\" from player {1}", key, identifier);
}
}// else = already removed
}
}
public void RemovePlayer(string identifier)
{
if (string.IsNullOrEmpty(identifier))
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Identifier is null or empty. Cannot remove player");
return;
}
bool playerLeftBool = false;
lock (playerData)
{
if (playerData[identifier] != null)
{
if (playerData.Remove(identifier))
{
playerLeftBool = true;
LiveMap.Log(LiveMap.LogLevel.Basic, "Removed player {0}", identifier);
}
else
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Couldn't remove player {0}... Seriously, there's something fucking wrong here...", identifier);
}
}
}
LiveMap.Log(LiveMap.LogLevel.All, "Notifying ws clients that a player left? {0}", playerLeftBool);
if (playerLeftBool)
{
JObject payload = new JObject();
payload["type"] = "playerLeft";
payload["payload"] = identifier;
sendQueue.Enqueue(payload);
}
}
private JObject ConvertBlip(dynamic blip)
{
JObject obj = new JObject();
JObject pos = new JObject();
pos["x"] = blip.pos.x;
pos["y"] = blip.pos.y;
pos["z"] = blip.pos.z;
if(blip.type != null)
{
obj["type"] = blip.type;
}
if (blip.name != null && !(string.IsNullOrEmpty(blip.name)))
{
obj["name"] = blip.name;
}
if (blip.description != null && !(string.IsNullOrEmpty(blip.description)))
{
obj["description"] = blip.description;
}
obj["pos"] = pos;
return obj;
}
public void AddBlip(dynamic blip)
{
if(blip == null)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot add blip as it's null");
return;
}
JObject payload = new JObject();
payload["type"] = "addBlip";
payload["payload"] = ConvertBlip(blip);
sendQueue.Enqueue(payload);
}
public void RemoveBlip(dynamic blip)
{
if (blip == null)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot remove blip as it's null");
return;
}
JObject payload = new JObject();
payload["type"] = "removeBlip";
payload["payload"] = ConvertBlip(blip);
sendQueue.Enqueue(payload);
}
public void UpdateBlip(dynamic blip)
{
if (blip == null)
{
LiveMap.Log(LiveMap.LogLevel.Basic, "Cannot update blip as it's null");
return;
}
JObject payload = new JObject();
payload["type"] = "updateBlip";
payload["payload"] = ConvertBlip(blip);
sendQueue.Enqueue(payload);
}
}
}