-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatManager.java
More file actions
909 lines (764 loc) · 33.7 KB
/
ChatManager.java
File metadata and controls
909 lines (764 loc) · 33.7 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
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/*This file could be considered the core of the application.
*Almost everything chat-app related happens here, managing the client, server, messages and reconnection.*/
package chat_app.backend;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.BindException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import readiefur.console.Logger;
import readiefur.misc.Event;
import readiefur.misc.IDisposable;
import readiefur.misc.ManualResetEvent;
import readiefur.misc.Pair;
import readiefur.sockets.Client;
import readiefur.sockets.ServerManager;
import chat_app.backend.net_data.EPeerStatus;
import chat_app.backend.net_data.EType;
import chat_app.backend.net_data.EmptyPayload;
import chat_app.backend.net_data.MessagePayload;
import chat_app.backend.net_data.NetMessage;
import chat_app.backend.net_data.PeersPayload;
public class ChatManager implements IDisposable
{
//#region Fields
private static final int COMMON_TIMEOUT = 1500;
private Boolean isDisposed = false;
private final Object lock = new Object();
//Constant properties (doesn't change between calling Restart()).
private final String fallbackServerIPAddress;
private final int port;
private final String desiredUsername;
private int failedRestarts = 0;
private Boolean isCleaningUp = false; //Required due to event loops in cleanup.
//Server specific properties.
private ServerManager serverManager = null;
private PingPong pingPong = null;
//Client specific properties.
private Client client = null;
private UUID id = null;
//Shared properties.
private Boolean isHost = true;
private ConcurrentHashMap<UUID, Peer> peers = new ConcurrentHashMap<>();
private ConcurrentHashMap<UUID, ManualResetEvent> pendingMessages = new ConcurrentHashMap<>();
//Events.
public final Event<Peer> onPeerConnected = new Event<>();
public final Event<Peer> onPeerDisconnected = new Event<>();
public final Event<MessagePayload> onMessageReceived = new Event<>();
//#endregion
//#region Startup/Shutdown
public ChatManager(String initialServerAddress, int port, String desiredUsername)
{
fallbackServerIPAddress = initialServerAddress;
this.port = port;
this.desiredUsername = desiredUsername; //If null, will be resolved to "Anonymous" later on.
}
@Override
public void Dispose()
{
synchronized (lock)
{
if (isDisposed)
return;
isDisposed = true;
Cleanup();
}
}
/**
* Starts the chat manager.
* Does not block the current thread.
*/
public void Begin()
{
//Start the manager.
Restart();
}
private void Cleanup()
{
isCleaningUp = true;
//Server related.
if (serverManager != null)
{
serverManager.onConnect.Remove(this::OnNetConnect);
serverManager.onMessage.Remove(this::OnNetMessage);
serverManager.onClose.Remove(this::OnNetClose);
serverManager.onError.Remove(this::OnNetError);
serverManager.Dispose();
// //Wait for the thread to finish.
// try { serverManager.join(); }
// catch (InterruptedException e) { Logger.Error("Failed to join server manager thread."); }
serverManager = null;
}
if (pingPong != null)
{
pingPong.interrupt();
// //Wait for the thread to finish.
// try { pingPong.join(); }
// catch (InterruptedException e) { Logger.Error("Failed to join ping pong thread."); }
pingPong = null;
}
//Client related.
if (client != null)
{
client.onConnect.Remove(nul -> OnNetConnect(ServerManager.SERVER_UUID));
client.onMessage.Remove(data -> OnNetMessage(new Pair<>(ServerManager.SERVER_UUID, data)));
client.onClose.Remove(nul -> OnNetClose(ServerManager.SERVER_UUID));
client.onError.Remove(error -> OnNetError(new Pair<>(ServerManager.SERVER_UUID, error)));
client.Dispose();
// //Wait for the thread to finish.
// try { client.join(); }
// catch (InterruptedException e) { Logger.Error("Failed to join client thread."); }
client = null;
}
//Shared.
id = null;
peers.clear();
isCleaningUp = false;
}
private void Restart()
{
synchronized (lock)
{
if (isDisposed)
return;
Logger.Trace("Restarting...");
UUID oldClientID = id;
List<Peer> oldPeers = new ArrayList<>(peers.values());
Cleanup();
/*Add some random time between x and y ms, this is to help prevent two servers trying to be created at the same time.
*While I do catch this issue if the server and client are on the same machine, if they are not then it is possible that,
*Two servers get made and the clients are split across servers which is not desirable.*/
/*In the future I think I would like to have this delay be based on the connection index (or GUID).
*Or if the server had a clean exit, tell which clients who will be the next host.*/
//We can skip this wait of the peersList was empty.
if (!oldPeers.isEmpty() && oldClientID != null)
{
//In order for the calculations below to work properly, at least one of the values needs to be a float.
//To make things easier however, I will make them all floats.
final float MIN_HASH_CODE = 0f;
final float MAX_HASH_CODE = Integer.MAX_VALUE;
final float MIN_SLEEP_TIME = 0f;
final float MAX_SLEEP_TIME = COMMON_TIMEOUT;
float clientHashCode = oldClientID.hashCode();
//We cannot work with negative numbers (and seeming as the randomness is great enough) we need to invert the number.
if (clientHashCode < 0)
clientHashCode = -clientHashCode;
//Convert the hash code to a value between MIN_HASH_CODE and MAX_HASH_CODE.
//https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
//NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
float sleepTime = (((clientHashCode - MIN_HASH_CODE) * (MAX_SLEEP_TIME - MIN_SLEEP_TIME)) / (MAX_HASH_CODE - MIN_HASH_CODE)) + MIN_SLEEP_TIME;
//Sonarlint wants me to replace this sleep call with a call to <lock>.wait(), however that is not suitable for this situation.
try { Thread.sleep((int)sleepTime); }
catch (InterruptedException e) {}
}
String hostAddress = null;
//Look for a host.
for (Peer peer : oldPeers)
{
UUID peerUUID = peer.GetUUID();
if (peerUUID.equals(ServerManager.INVALID_UUID) //We don't include the server ID as a check as we may have accidentally lost connection.
|| (oldClientID != null && peerUUID.equals(oldClientID))) //We don't check ourself.
continue;
String peerAddress = peer.GetIPAddress();
if (FindHost(hostAddress, port))
{
hostAddress = peerAddress;
break;
}
}
//If a host was not found on one of the previous peers, check if a fallback server was passed and is valid.
if (hostAddress == null && fallbackServerIPAddress != null && FindHost(fallbackServerIPAddress, port))
hostAddress = fallbackServerIPAddress;
//If a host was not found, begin hosting.
isHost = hostAddress == null;
if (isHost)
{
Logger.Trace("No host found, starting server...");
//Start the server.
serverManager = new ServerManager(port);
serverManager.onConnect.Add(this::OnNetConnect);
serverManager.onMessage.Add(this::OnNetMessage);
serverManager.onClose.Add(this::OnNetClose);
serverManager.onError.Add(this::OnNetError);
String serverAddress;
try { serverAddress = Inet4Address.getLocalHost().getHostAddress(); }
catch (UnknownHostException e) { serverAddress = fallbackServerIPAddress; }
id = ServerManager.SERVER_UUID;
ServerPeer serverPeer = new ServerPeer(
ServerManager.SERVER_UUID,
serverAddress,
desiredUsername,
EPeerStatus.CONNECTED);
peers.put(ServerManager.SERVER_UUID, serverPeer);
if (!serverManager.Start())
{
failedRestarts++;
Logger.Trace(GetLogPrefix() + "Failed to start server: " + failedRestarts + "/3");
if (failedRestarts >= 3)
throw new RuntimeException("Failed to start server.");
Restart();
return;
}
Logger.Trace(GetLogPrefix() + "Server started.");
onPeerConnected.Invoke(ServerPeer.ToPeer(serverPeer));
//TODO: Ensure this gets enabled when finished with debugging.
pingPong = new PingPong(serverManager);
pingPong.start();
Logger.Trace(GetLogPrefix() + "PingPong started.");
}
else
{
Logger.Trace("Host found at " + hostAddress + ":" + port + ". Connecting...");
//Connect to the server.
client = new Client(hostAddress, port);
client.onConnect.Add(nul -> OnNetConnect(ServerManager.SERVER_UUID));
client.onMessage.Add(data -> OnNetMessage(new Pair<>(ServerManager.SERVER_UUID, data)));
client.onClose.Add(nul -> OnNetClose(ServerManager.SERVER_UUID));
client.onError.Add(error -> OnNetError(new Pair<>(ServerManager.SERVER_UUID, error)));
if (!client.Start())
{
failedRestarts++;
Logger.Trace(GetLogPrefix() + "Failed to start client: " + failedRestarts + "/3");
if (failedRestarts >= 3)
throw new RuntimeException("Failed to start client.");
Restart();
return;
}
Logger.Trace(GetLogPrefix() + "Client started.");
}
Logger.Info("[CHAT_MANAGER] Promoted to " + (isHost ? "host" : "client") + ".");
failedRestarts = 0;
}
}
private Boolean FindHost(String ipAddress, int port)
{
if (ipAddress == null)
return false;
Logger.Trace("Looking for host at " + ipAddress + ":" + port + "...");
ManualResetEvent resetEvent = new ManualResetEvent(false);
Client dummyClient = new Client(ipAddress, port);
dummyClient.onConnect.Add(nul -> resetEvent.Set());
if (!dummyClient.Start())
return false;
try { resetEvent.WaitOne(1000); }
catch (TimeoutException e) {}
Boolean hostFound = dummyClient.IsConnected();
dummyClient.Dispose();
return hostFound;
}
//#endregion
//#region Network Events
private void OnNetConnect(UUID uuid)
{
if (isDisposed || isCleaningUp)
return;
Logger.Trace(GetLogPrefix() + "Connection opened: " + uuid);
if (isHost)
{
/*When a new client connects, we add them to the list of peers however we don't,
*indicate that the client is ready yet, we must wait for the handshake first.*/
peers.put(uuid, new ServerPeer(
uuid,
serverManager.GetClientHosts().get(uuid).GetSocket().getLocalAddress().getHostAddress(),
desiredUsername,
EPeerStatus.UNINITIALIZED));
}
else
{
//Send the handshake (this event will only occur when connecting to the server).
NetMessage<Peer> message = new NetMessage<>();
message.type = EType.HANDSHAKE;
message.payload = new Peer(desiredUsername);
client.SendMessage(message);
///See: OnNetMessage > Host > HANDSHAKE
}
}
private void OnNetMessage(Pair<UUID, Object> data)
{
if (isDisposed || isCleaningUp)
return;
//Verify that the message body is a typeof(NetMessage<?>)
if (!(data.item2 instanceof NetMessage<?>))
return;
@SuppressWarnings("unchecked")
Pair<UUID, NetMessage<?>> castData = (Pair<UUID, NetMessage<?>>)(Object)data;
/*If the message isn't a EType.MESSAGE and the sender isn't the server,
*ignore the request as clients should not be allowed to send other events to each other.*/
if (!isHost && castData.item2.type != EType.MESSAGE && !data.item1.equals(ServerManager.SERVER_UUID))
return;
Logger.Trace(GetLogPrefix() + "Message received: " + castData.item1 + " | " + castData.item2.type);
switch (castData.item2.type)
{
case HANDSHAKE:
{
//Annoying how this can't be used inline.
// @SuppressWarnings("unchecked")
HandleHandshakeData((Pair<UUID, NetMessage<Peer>>)(Object)castData);
break;
}
case PING:
{
// @SuppressWarnings("unchecked")
HandlePingData((Pair<UUID, NetMessage<EmptyPayload>>)(Object)castData);
break;
}
case PONG:
{
//The host handles pong messages via the PingPong class.
//Clients do not need to handle pong messages.
break;
}
case PEER:
{
// @SuppressWarnings("unchecked")
HandlePeerData((Pair<UUID, NetMessage<Peer>>)(Object)castData);
break;
}
case PEERS:
{
// @SuppressWarnings("unchecked")
HandlePeersData((Pair<UUID, NetMessage<PeersPayload>>)(Object)castData);
break;
}
case MESSAGE:
{
// @SuppressWarnings("unchecked")
HandleMessageData((Pair<UUID, NetMessage<MessagePayload>>)(Object)castData);
break;
}
default:
//Invalid message type, ignore the request.
break;
}
}
//#region Message specific methods.
//The net message handler has been split off into multiple methods as its body would've been massive otherwise, this is to improve readability.
private void HandleHandshakeData(Pair<UUID, NetMessage<Peer>> data)
{
if (isHost)
{
//From: OnNetConnect > Client
ServerPeer peer = (ServerPeer)peers.get(data.item1);
//If the peer isn't found then ignore the request || If the peer has already handshaked (connected), ignore the request.
if (peer == null || peer.GetStatus() == EPeerStatus.CONNECTED)
return;
String nickname = data.item2.payload.username == null || data.item2.payload.username.isBlank()
? "Anonymous" : data.item2.payload.username;
int duplicateCount = 0;
/*Check for duplicate nicknames.
*(This could've been done ine like 2 lines in C# but Java's inability to pass local variables makes it a bit more complicated).*/
while (true)
{
boolean duplicateFound = false;
for (Peer existingPeer : peers.values())
{
//It seems like string == string is not the same as string.equals(string) in Java.
if (existingPeer.GetStatus() == EPeerStatus.CONNECTED
&& existingPeer.username != null
&& existingPeer.username.equals(nickname))
{
duplicateFound = true;
break;
}
}
if (!duplicateFound)
break;
nickname = data.item2.payload.username + (++duplicateCount);
}
//Indicate that the client is ready.
//All peers should be typeof ServerPeer at this level.
peer.username = nickname;
peer.SetStatus(EPeerStatus.CONNECTED);
Logger.Debug(GetLogPrefix() + "Client connected: " + data.item1 + " (" + peer.username + ")");
Logger.Info(GetLogPrefix() + "Client connected: " + peer.username);
//Return the server-validated handshake data back to the client.
NetMessage<Peer> response = new NetMessage<>();
response.type = EType.HANDSHAKE;
response.payload = peer;
serverManager.SendMessage(data.item1, response);
///See: OnNetMessage > Client > HANDSHAKE
//Broadcast the new peer to all other peers.
NetMessage<Peer> peerBroadcast = new NetMessage<>();
peerBroadcast.type = EType.PEER;
peerBroadcast.payload = peer;
serverManager.BroadcastMessage(peerBroadcast);
///See: OnNetMessage > Client > PEER
onPeerConnected.Invoke(ServerPeer.ToPeer(peer));
}
else
{
//From: OnNetMessage > Host > HANDSHAKE
id = data.item2.payload.GetUUID();
Logger.Trace("Connected to server and assigned ID: " + id);
Logger.Info(GetLogPrefix() + "Connected to server.");
//Occurs when the handshake has been acknowledged by the server.
//Request a list of peers.
NetMessage<EmptyPayload> response = new NetMessage<>();
response.type = EType.PEERS;
response.payload = new EmptyPayload();
client.SendMessage(response);
///See: OnNetMessage > Host > PEERS
}
}
private void HandlePingData(Pair<UUID, NetMessage<EmptyPayload>> data)
{
if (isHost)
{
//Host pings are handled by the PingPong class.
}
else
{
//Occurs when the server has sent a ping request.
//TODO: Add a timer to check if the server has timed out.
//Return a pong.
NetMessage<EmptyPayload> response = new NetMessage<>();
response.type = EType.PONG;
response.payload = new EmptyPayload();
client.SendMessage(response);
}
}
private void HandlePeerData(Pair<UUID, NetMessage<Peer>> data)
{
if (isHost)
{
}
else
{
/*It is more efficient to store this value in a local variable rather than call
*the method multiple times as it converts a string value every time.*/
UUID payloadID = data.item2.payload.GetUUID();
switch (data.item2.payload.GetStatus())
{
case CONNECTED:
{
//If the client wasn't in the list then fire the connect event (this includes us connecting to the server).
Boolean isNewPeer = !peers.containsKey(payloadID) && !payloadID.equals(ServerManager.SERVER_UUID);
//Update the peer in the list (this should be added before the OnNetConnect event is fired).
/*Notice how there is no synchronize block here, this is because I am using a ConcurrentHashMap which is synchronized
*and I am not performing any long operations here so there is no need use a synchronize block here.*/
peers.put(payloadID, data.item2.payload);
if (isNewPeer)
onPeerConnected.Invoke(data.item2.payload);
break;
}
case DISCONNECTED:
{
//Remove the peer from the list and fire the disconnect event if we had the peer.
if (!peers.containsKey(payloadID))
return;
//In this case the event must be fired before the peer is removed from the list.
OnNetClose(payloadID);
break;
}
default:
{
//Ignore the message.
break;
}
}
}
}
private void HandlePeersData(Pair<UUID, NetMessage<PeersPayload>> data)
{
if (isHost)
{
//(Typically) From: OnNetMessage > Client > HANDSHAKE
//Send the list of peers to the client.
NetMessage<PeersPayload> response = new NetMessage<>();
response.type = EType.PEERS;
response.payload = new PeersPayload();
response.payload.peers = GetReadyPeers();
serverManager.SendMessage(data.item1, response);
///See: OnNetMessage > Client > PEERS
}
else
{
//From: OnNetMessage > Host > PEERS
//Occurs when the server has sent a new list of peers.
/*The reason for having a separate PEER and PEERS message is so that the server can send a list of peers,
*which is more efficient than sending a PEER message for each peer.*/
//Replace the list of peers with the new list.
HashMap<UUID, Peer> oldPeers = new HashMap<>(peers);
peers.clear();
for (Peer peer : data.item2.payload.peers)
{
//In my testing it seemed like the payload would include one extra null value.
if (peer == null)
continue;
UUID peerUUID = peer.GetUUID();
peers.put(peerUUID, peer);
//We don't need to check the state of the peer as they should always be connected at this point.
if (!oldPeers.containsKey(peerUUID))
onPeerConnected.Invoke(peer);
}
/*If the client was in the old list but not the new one, fire the disconnect event.
*While this shouldn't strictly be relied on for disconnect events (as the peer message should send this status update
*it is a good idea to check it here just incase the message is missed.*/
for (UUID peerUUID : oldPeers.keySet())
if (!peerUUID.equals(id) && !peerUUID.equals(ServerManager.SERVER_UUID) && !peers.containsKey(peerUUID))
OnNetClose(peerUUID);
}
}
private void HandleMessageData(Pair<UUID, NetMessage<MessagePayload>> data)
{
if (isHost)
{
//Occurs when a client sends a message to be processed by the server.
//Ignore messages from clients who have not connected yet.
if (peers.get(data.item1).GetStatus() != EPeerStatus.CONNECTED)
return;
data.item2.payload.SetSender(data.item1);
UUID recipient = data.item2.payload.GetRecipient();
/*If the recipient is `INVALID_UUID` then broadcast the message to all peers.
*Otherwise check if the message is available to be sent to the specified peer.*/
if (recipient.equals(ServerManager.INVALID_UUID))
{
//Broadcast the message to all peers.
NetMessage<MessagePayload> message = new NetMessage<>();
message.type = EType.MESSAGE;
message.payload = data.item2.payload;
serverManager.BroadcastMessage(message);
//See: OnNetMessage > Host/Client > MESSAGE
//If we (the server) are the sender then remove the message from the queue.
//Otherwise invoke the OnMessageReceived event.
if (data.item2.payload.GetSender().equals(ServerManager.SERVER_UUID))
ClearPendingMessage(data.item2.payload.GetMessageID());
else
onMessageReceived.Invoke(data.item2.payload);
}
else if (peers.containsKey(recipient) && peers.get(recipient).GetStatus() == EPeerStatus.CONNECTED)
{
//If the sender is us, forward the message to the recipient and remove the message from the queue.
if (data.item2.payload.GetSender().equals(ServerManager.SERVER_UUID))
{
serverManager.SendMessage(recipient, data.item2);
//See: OnNetMessage > Client > MESSAGE > else
ClearPendingMessage(data.item2.payload.GetMessageID());
return;
}
//Else if the recipient is us, invoke the OnMessageReceived event.
//Otherwise forward the message to the specified peer.
if (recipient.equals(ServerManager.SERVER_UUID))
{
onMessageReceived.Invoke(data.item2.payload);
}
else
{
serverManager.SendMessage(recipient, data.item2.payload);
//See: OnNetMessage > Client > MESSAGE > else
}
//Also send the message back to the sender to indicate that the message has been acknowledged.
serverManager.SendMessage(data.item1, data.item2);
//See: OnNetMessage > Client > MESSAGE > if
}
//Otherwise ignore the request.
}
else
{
//Occurs when the server has sent a message to the client.
UUID messageID = data.item2.payload.GetMessageID();
UUID sender = data.item2.payload.GetSender();
//If the sender is us, we can use this response to verify that the message was sent.
//Otherwise we can invoke the message event.
if (sender.equals(id))
ClearPendingMessage(messageID);
else
onMessageReceived.Invoke(data.item2.payload);
}
}
//#endregion
private void OnNetClose(UUID uuid)
{
if (isDisposed || isCleaningUp)
return;
Logger.Trace(GetLogPrefix() + "Connection closed: " + uuid);
Peer oldPeer = peers.get(uuid);
if (oldPeer == null)
return;
if (isHost)
{
//Server has closed, handled in OnNetError || Can occur for server lookups.
if (uuid.equals(ServerManager.SERVER_UUID) || !peers.containsKey(uuid))
return;
//Client has disconnected.
peers.remove(uuid);
//If the client wasn't a connected peer then don't broadcast the disconnect (this can occur for handshake requests).
if (oldPeer.GetStatus() != EPeerStatus.CONNECTED)
return;
//The oldPeer variable will be a ServerPeer object at this level.
((ServerPeer)oldPeer).SetStatus(EPeerStatus.DISCONNECTED);
Logger.Debug(GetLogPrefix() + "Client disconnected: " + uuid + " (" + oldPeer.GetUsername() + ")");
Logger.Info(GetLogPrefix() + "Client disconnected: " + oldPeer.GetUsername());
//Broadcast the disconnected peer to all other clients.
NetMessage<Peer> peerBroadcast = new NetMessage<>();
peerBroadcast.type = EType.PEER;
peerBroadcast.payload = ServerPeer.ToPeer(((ServerPeer)oldPeer));
serverManager.BroadcastMessage(peerBroadcast);
}
else
{
//If the server has disconnected, restart the client.
if (uuid.equals(ServerManager.SERVER_UUID))
{
Logger.Info(GetLogPrefix() + "Disconnected from server.");
//In this case we need to invoke the disconnect event before restarting.
onPeerDisconnected.Invoke(oldPeer);
Restart();
return;
}
//Otherwise a client has disconnected, in which case we check if they were in our peers list, if they were then we remove them.
if (!peers.containsKey(uuid))
return;
peers.remove(uuid);
Logger.Trace(GetLogPrefix() + "Peer disconnected: " + uuid + " (" + oldPeer.GetUsername() + ")");
Logger.Info(GetLogPrefix() + "Peer disconnected: " + oldPeer.GetUsername());
}
//If the above code hasn't returned, then we can invoke the disconnect event.
onPeerDisconnected.Invoke(oldPeer);
}
private void OnNetError(Pair<UUID, Exception> error)
{
if (isHost)
{
if (error.item2 instanceof BindException)
{
/*A bind error can occur when another server is already running on the same port
*if this happens, assume another server instance is running.
*The restart will be called by the false returned Start method, so we don't call a restart here.*/
return;
}
}
//Print the stack trace to a custom stream.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintStream stream = new PrintStream(byteStream);
error.item2.printStackTrace(stream);
//Get the stack trace as a string.
String stackTrace = byteStream.toString();
//Dispose of the streams.
stream.close();
try { byteStream.close(); }
catch (IOException e) {}
//Log the error.
Logger.Error(GetLogPrefix() + "Error in connection: " + error.item1 + " | " + stackTrace);
}
//#endregion
//#region Misc
private Peer[] GetReadyPeers()
{
List<Peer> readyPeers = new ArrayList<>();
for (Peer peer : peers.values())
{
if (peer.GetStatus() != EPeerStatus.CONNECTED)
continue;
if (peer instanceof ServerPeer)
readyPeers.add(ServerPeer.ToPeer((ServerPeer)peer));
else
readyPeers.add(peer);
}
return readyPeers.toArray(new Peer[readyPeers.size()]);
}
private String GetLogPrefix()
{
return "[" + (isHost ? "SERVER" : "CLIENT") + "] ";
}
/**
* Returns a copy of the current peers list.
* @return
*/
public Map<UUID, Peer> GetPeers()
{
return new HashMap<>(peers);
}
/**
* Returns whether or not we are currently the host.
*/
public Boolean IsHost()
{
return isHost;
}
public UUID GetID()
{
return id;
}
/**
* Returns whether or not the server has been disposed.
*/
public Boolean IsDisposed()
{
return isDisposed;
}
/**
* Sends a message to the specified recipient and waits for the server to acknowledge the message.
* @return {@code true} if the message was sent successfully, otherwise {@code false}.
*/
public Boolean SendMessageSync(UUID recipient, String message)
{
return SendMessageInternal(recipient, message, true);
}
/**
* Sends a message to the specified recipient and does not wait for the server to acknowledge the message.
*/
public void SendMessage(UUID recipient, String message)
{
SendMessageInternal(recipient, message, false);
}
private Boolean SendMessageInternal(UUID recipient, String message, Boolean sendSync)
{
MessagePayload payload = new MessagePayload(recipient, message);
NetMessage<MessagePayload> netMessage = new NetMessage<>();
netMessage.type = EType.MESSAGE;
netMessage.payload = payload;
//If we want to send the message synchronously, setup the ManualResetEvent to wait on.
ManualResetEvent messageSentEvent = null; //Required to satisfy the compiler, the bang nullable operator would've been nice here (C# feature).
if (sendSync)
{
messageSentEvent = new ManualResetEvent(false);
pendingMessages.put(payload.GetMessageID(), messageSentEvent);
}
if (isHost)
{
//If we are the server, we have no way of "sending messages to ourself", so we can just call the OnNetMessage method directly.
OnNetMessage(new Pair<>(ServerManager.SERVER_UUID, netMessage));
}
else
{
client.SendMessage(netMessage);
///See: OnNetMessage > Host > MESSAGE
}
//If we are not sending the message synchronously, return true here.
if (!sendSync)
return true;
//Otherwise wait for the server to acknowledge the message (within the time limit, currently hardcoded).
try
{
messageSentEvent.WaitOne(COMMON_TIMEOUT);
return true;
}
catch (TimeoutException e)
{
Logger.Warn("Failed to send message: " + payload.GetMessageID());
return false;
}
finally
{
//Remove the message from the pending messages list.
pendingMessages.remove(payload.GetMessageID());
}
}
private void ClearPendingMessage(UUID messageID)
{
if (!pendingMessages.containsKey(messageID))
return;
pendingMessages.get(messageID).Set();
pendingMessages.remove(messageID);
}
//#endregion
}