forked from TehGimp/KerbalMultiPlayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMPClientMain.cs
1917 lines (1589 loc) · 54.6 KB
/
KMPClientMain.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
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using KSP.IO;
using UnityEngine;
namespace KMP
{
class KMPClientMain
{
public struct InTextMessage
{
public bool fromServer;
public String message;
}
public struct ServerMessage
{
public KMPCommon.ServerMessageID id;
public byte[] data;
}
//Constants
public const String USERNAME_LABEL = "username";
public const String IP_LABEL = "ip";
public const String AUTO_RECONNECT_LABEL = "reconnect";
public const String FAVORITE_LABEL = "fav";
//public const String INTEROP_CLIENT_FILENAME = "interopclient.txt";
//public const String INTEROP_PLUGIN_FILENAME = "interopplugin.txt";
public const String CLIENT_CONFIG_FILENAME = "KMPClientConfig.txt";
public const String CLIENT_TOKEN_FILENAME = "KMPPlayerToken.txt";
public const String PART_LIST_FILENAME = "KMPPartList.txt";
public const String CRAFT_FILE_EXTENSION = ".craft";
public const int MAX_USERNAME_LENGTH = 16;
public const int MAX_TEXT_MESSAGE_QUEUE = 128;
public const long KEEPALIVE_DELAY = 2000;
public const long UDP_PROBE_DELAY = 1000;
public const long UDP_TIMEOUT_DELAY = 8000;
public const int SLEEP_TIME = 5;
public const int CLIENT_DATA_FORCE_WRITE_INTERVAL = 10000;
public const int RECONNECT_DELAY = 1000;
public const int MAX_RECONNECT_ATTEMPTS = 0;
public const long PING_TIMEOUT_DELAY = 10000;
public const int INTEROP_WRITE_INTERVAL = 333;
public const int INTEROP_MAX_QUEUE_SIZE = 64;
public const int MAX_QUEUED_CHAT_LINES = 8;
public const int DEFAULT_PORT = 2076;
//public const String PLUGIN_DIRECTORY = "PluginData/kerbalmultiplayer/";
public static UnicodeEncoding encoder = new UnicodeEncoding();
//Settings
private static String mUsername = "";
private static Guid playerGuid;
public static String username
{
set
{
if (value != null && value.Length > MAX_USERNAME_LENGTH)
mUsername = value.Substring(0, MAX_USERNAME_LENGTH);
else
mUsername = value;
}
get
{
return mUsername;
}
}
public static String hostname = "localhost";
public static int updateInterval = 100;
public static int screenshotInterval = 1000;
public static bool autoReconnect = true;
public static byte inactiveShipsPerUpdate = 0;
public static ScreenshotSettings screenshotSettings = new ScreenshotSettings();
public static String[] favorites = new String[8];
//Connection
public static int clientID;
public static bool endSession;
public static bool intentionalConnectionEnd;
public static bool handshakeCompleted;
public static Socket tcpSocket;
public static long lastTCPMessageSendTime;
public static bool quitHelperMessageShow;
public static int reconnectAttempts;
public static Socket udpSocket;
public static bool udpConnected;
public static long lastUDPMessageSendTime;
public static long lastUDPAckReceiveTime;
public static bool receivedSettings;
//Plugin Interop
public static Queue<byte[]> interopOutQueue;
public static long lastInteropWriteTime;
public static Queue<byte[]> interopInQueue;
public static Queue<byte[]> pluginUpdateInQueue;
public static Queue<InTextMessage> textMessageQueue;
public static long lastScreenshotShareTime;
public static byte[] queuedOutScreenshot;
public static byte[] lastSharedScreenshot;
public static String currentGameTitle;
public static String watchPlayerName;
public static long lastClientDataWriteTime;
public static long lastClientDataChangeTime;
public static String message = "Not connected";
//Messages
public static Queue<ServerMessage> receivedMessageQueue;
public static byte[] currentMessageHeader = new byte[KMPCommon.MSG_HEADER_LENGTH];
public static int currentMessageHeaderIndex;
public static byte[] currentMessageData;
public static int currentMessageDataIndex;
public static KMPCommon.ServerMessageID currentMessageID;
private static byte[] receiveBuffer = new byte[8192];
private static int receiveIndex = 0;
private static int receiveHandleIndex = 0;
//Threading
public static object tcpSendLock = new object();
public static object serverSettingsLock = new object();
public static object screenshotOutLock = new object();
public static object threadExceptionLock = new object();
public static object clientDataLock = new object();
public static object udpTimestampLock = new object();
public static object receiveBufferLock = new object();
public static object debugLogLock = new object();
public static object interopOutQueueLock = new object();
public static String threadExceptionStackTrace;
public static Exception threadException;
public static Thread serverThread;
public static Thread interopThread;
public static Thread chatThread;
public static Thread connectionThread;
public static Stopwatch stopwatch;
public static Stopwatch pingStopwatch = new Stopwatch();
public static KMPManager gameManager;
public static long lastPing;
public static bool debugging = true;
public static List<string> partList = new List<string>();
public static void InitMPClient(KMPManager manager)
{
gameManager = manager;
UnityEngine.Debug.Log("KMP Client version " + KMPCommon.PROGRAM_VERSION);
UnityEngine.Debug.Log(" Created by Shaun Esau");
UnityEngine.Debug.Log(" Based on Kerbal LiveFeed created by Alfred Lam");
stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < favorites.Length; i++)
favorites[i] = String.Empty;
}
public static String GetUsername()
{
readConfigFile();
return username;
}
public static void SetUsername(String newUsername)
{
username = newUsername;
if (username.Length > MAX_USERNAME_LENGTH)
username = username.Substring(0, MAX_USERNAME_LENGTH); //Trim username
writeConfigFile();
}
public static void SetServer(String newHostname)
{
hostname = newHostname;
writeConfigFile();
}
public static void SetAutoReconnect(bool newAutoReconnect)
{
autoReconnect = newAutoReconnect;
writeConfigFile();
}
public static String[] GetFavorites()
{
return favorites;
}
public static void SetFavorites(String[] newFavorites)
{
favorites = newFavorites;
writeConfigFile();
}
public static void Connect()
{
clearConnectionState();
File.Delete<KMPClientMain>("debug");
serverThread = new Thread(beginConnect);
serverThread.Start();
}
private static void beginConnect()
{
SetMessage("Attempting to connect...");
bool allow_reconnect = false;
reconnectAttempts = MAX_RECONNECT_ATTEMPTS;
do
{
allow_reconnect = false;
try
{
//Run the connection loop then determine if a reconnect attempt should be made
if (connectionLoop())
{
reconnectAttempts = 0;
allow_reconnect = autoReconnect && !intentionalConnectionEnd && reconnectAttempts < MAX_RECONNECT_ATTEMPTS;
}
else
allow_reconnect = autoReconnect && !intentionalConnectionEnd && reconnectAttempts < MAX_RECONNECT_ATTEMPTS;
}
catch (Exception e)
{
//Write an error log
KSP.IO.TextWriter writer = KSP.IO.File.AppendText<KMPClientMain>("KMPClientlog.txt");
writer.WriteLine(e.ToString());
if (threadExceptionStackTrace != null && threadExceptionStackTrace.Length > 0)
{
writer.WriteLine("KMP Stacktrace: ");
writer.WriteLine(threadExceptionStackTrace);
}
writer.Close();
UnityEngine.Debug.LogError(e.ToString());
if (threadExceptionStackTrace != null && threadExceptionStackTrace.Length > 0)
{
UnityEngine.Debug.Log(threadExceptionStackTrace);
}
UnityEngine.Debug.LogError("Unexpected exception encountered! Crash report written to KMPClientlog.txt");
}
if (allow_reconnect)
{
//Attempt a reconnect after a delay
SetMessage("Attempting to reconnect...");
Thread.Sleep(RECONNECT_DELAY);
reconnectAttempts++;
}
} while (allow_reconnect);
}
/// <summary>
/// Connect to the server and run a session until the connection ends
/// </summary>
/// <returns>True iff a connection was successfully established with the server</returns>
static bool connectionLoop()
{
//Look for a port-number in the hostname
int port = DEFAULT_PORT;
String trimmed_hostname = hostname;
int port_start_index = hostname.LastIndexOf(':');
if (port_start_index >= 0 && port_start_index < (hostname.Length - 1))
{
String port_substring = hostname.Substring(port_start_index + 1);
if (!int.TryParse(port_substring, out port) || port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
port = DEFAULT_PORT;
trimmed_hostname = hostname.Substring(0, port_start_index);
}
//Look up the actual IP address
IPHostEntry host_entry = new IPHostEntry();
try
{
host_entry = Dns.GetHostEntry(trimmed_hostname);
}
catch (SocketException)
{
host_entry = null;
}
catch (ArgumentException)
{
host_entry = null;
}
IPAddress address = null;
if (host_entry != null && host_entry.AddressList.Length == 1)
address = host_entry.AddressList.First();
else
IPAddress.TryParse(trimmed_hostname, out address);
if (address == null) {
SetMessage("Invalid server address.");
return false;
}
IPEndPoint endpoint = new IPEndPoint(address, port);
SetMessage("Connecting to server: " + address + ":" + port);
try
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(endpoint);
tcpSocket = tcpClient.Client;
if (tcpSocket.Connected)
{
clientID = -1;
endSession = false;
intentionalConnectionEnd = false;
handshakeCompleted = false;
receivedSettings = false;
pluginUpdateInQueue = new Queue<byte[]>();
textMessageQueue = new Queue<InTextMessage>();
lock (interopOutQueueLock)
{
interopOutQueue = new Queue<byte[]>();
}
interopInQueue = new Queue<byte[]>();
receivedMessageQueue = new Queue<ServerMessage>();
threadException = null;
currentGameTitle = String.Empty;
watchPlayerName = String.Empty;
lastSharedScreenshot = null;
lastScreenshotShareTime = 0;
lastTCPMessageSendTime = 0;
lastClientDataWriteTime = 0;
lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
quitHelperMessageShow = true;
//Init udp socket
try
{
udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpSocket.Connect(endpoint);
}
catch
{
if (udpSocket != null)
udpSocket.Close();
udpSocket = null;
}
udpConnected = false;
lastUDPAckReceiveTime = 0;
lastUDPMessageSendTime = stopwatch.ElapsedMilliseconds;
//Create a thread to handle chat
chatThread = new Thread(new ThreadStart(handleChat));
chatThread.Start();
//Create a thread to handle client interop
interopThread = new Thread(new ThreadStart(handlePluginInterop));
interopThread.Start();
//Create a thread to handle disconnection
connectionThread = new Thread(new ThreadStart(handleConnection));
connectionThread.Start();
beginAsyncRead();
SetMessage("Connected to server! Handshaking...");
while (!endSession && !intentionalConnectionEnd && tcpSocket.Connected)
{
//Check for exceptions thrown by threads
lock (threadExceptionLock)
{
if (threadException != null)
{
Exception e = threadException;
threadExceptionStackTrace = e.StackTrace;
throw e;
}
}
Thread.Sleep(SLEEP_TIME);
}
//clearConnectionState();
if (intentionalConnectionEnd)
enqueuePluginChatMessage("Closed connection with server", true);
else
enqueuePluginChatMessage("Lost connection with server", true);
return true;
}
}
catch (Exception)
{
SetMessage("Disconnected");
if (tcpSocket != null)
tcpSocket.Close();
tcpSocket = null;
}
return false;
}
static void handleMessage(KMPCommon.ServerMessageID id, byte[] data)
{
//LogAndShare("Message ID: " + id.ToString() + " data: " + (data == null ? "0" : System.Text.Encoding.ASCII.GetString(data)));
switch (id)
{
case KMPCommon.ServerMessageID.HANDSHAKE:
Int32 protocol_version = KMPCommon.intFromBytes(data);
if (data.Length >= 8)
{
Int32 server_version_length = KMPCommon.intFromBytes(data, 4);
if (data.Length >= 12 + server_version_length)
{
String server_version = encoder.GetString(data, 8, server_version_length);
clientID = KMPCommon.intFromBytes(data, 8 + server_version_length);
SetMessage("Handshake received. Server version: " + server_version);
}
}
//End the session if the protocol versions don't match
if (protocol_version != KMPCommon.NET_PROTOCOL_VERSION)
{
endSession = true;
intentionalConnectionEnd = true;
}
else
{
sendHandshakeMessage(); //Reply to the handshake
lock (udpTimestampLock)
{
lastUDPMessageSendTime = stopwatch.ElapsedMilliseconds;
}
handshakeCompleted = true;
}
break;
case KMPCommon.ServerMessageID.HANDSHAKE_REFUSAL:
String refusal_message = encoder.GetString(data, 0, data.Length);
endSession = true;
intentionalConnectionEnd = true;
enqueuePluginChatMessage("Server refused connection. Reason: " + refusal_message, true);
break;
case KMPCommon.ServerMessageID.SERVER_MESSAGE:
case KMPCommon.ServerMessageID.TEXT_MESSAGE:
if (data != null)
{
InTextMessage in_message = new InTextMessage();
in_message.fromServer = (id == KMPCommon.ServerMessageID.SERVER_MESSAGE);
in_message.message = encoder.GetString(data, 0, data.Length);
//Queue the message
enqueueTextMessage(in_message);
}
break;
case KMPCommon.ServerMessageID.PLUGIN_UPDATE:
if (data != null)
enqueueClientInteropMessage(KMPCommon.ClientInteropMessageID.PLUGIN_UPDATE, data);
break;
case KMPCommon.ServerMessageID.SERVER_SETTINGS:
lock (serverSettingsLock)
{
if (data != null && data.Length >= KMPCommon.SERVER_SETTINGS_LENGTH && handshakeCompleted)
{
updateInterval = KMPCommon.intFromBytes(data, 0);
screenshotInterval = KMPCommon.intFromBytes(data, 4);
lock (clientDataLock)
{
int new_screenshot_height = KMPCommon.intFromBytes(data, 8);
if (screenshotSettings.maxHeight != new_screenshot_height)
{
screenshotSettings.maxHeight = new_screenshot_height;
lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
enqueueTextMessage("Screenshot Height has been set to " + screenshotSettings.maxHeight);
}
if (inactiveShipsPerUpdate != data[12])
{
inactiveShipsPerUpdate = data[12];
lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
}
}
receivedSettings = true;
/*
UnityEngine.Debug.Log("Update interval: " + updateInterval);
UnityEngine.Debug.Log("Screenshot interval: " + screenshotInterval);
UnityEngine.Debug.Log("Inactive ships per update: " + inactiveShipsPerUpdate);
*/
}
}
break;
case KMPCommon.ServerMessageID.SCREENSHOT_SHARE:
if (data != null && data.Length > 0 && data.Length < screenshotSettings.maxNumBytes
&& watchPlayerName.Length > 0 && watchPlayerName != username)
{
enqueueClientInteropMessage(KMPCommon.ClientInteropMessageID.SCREENSHOT_RECEIVE, data);
}
break;
case KMPCommon.ServerMessageID.CONNECTION_END:
gameManager.disconnect();
if (data != null)
{
String message = encoder.GetString(data, 0, data.Length);
endSession = true;
handshakeCompleted = false;
receivedSettings = false;
//If the reason is not a timeout, connection end is intentional
intentionalConnectionEnd = message.ToLower() != "timeout";
enqueuePluginChatMessage("Server closed the connection: " + message, true);
clearConnectionState();
SetMessage("Disconnected from server: " + message);
gameManager.disconnect(message);
}
else
{
clearConnectionState();
SetMessage("Disconnected from server");
gameManager.disconnect();
}
break;
case KMPCommon.ServerMessageID.UDP_ACKNOWLEDGE:
lock (udpTimestampLock)
{
lastUDPAckReceiveTime = stopwatch.ElapsedMilliseconds;
}
break;
case KMPCommon.ServerMessageID.CRAFT_FILE:
if (data != null && data.Length > 4)
{
//Read craft name length
byte craft_type = data[0];
int craft_name_length = KMPCommon.intFromBytes(data, 1);
if (craft_name_length < data.Length - 5)
{
//Read craft name
String craft_name = encoder.GetString(data, 5, craft_name_length);
//Read craft bytes
byte[] craft_bytes = new byte[data.Length - craft_name_length - 5];
Array.Copy(data, 5 + craft_name_length, craft_bytes, 0, craft_bytes.Length);
//Write the craft to a file
String filename = getCraftFilename(craft_name, craft_type);
if (filename != null)
{
try
{
//KSP.IO.File.WriteAllBytes<KMPClientMain>(craft_bytes, filename);
System.IO.File.WriteAllBytes(filename,craft_bytes);
enqueueTextMessage("Received craft file: " + craft_name);
}
catch
{
enqueueTextMessage("Error saving received craft file: " + craft_name);
}
}
else
enqueueTextMessage("Unable to save received craft file.");
}
}
break;
case KMPCommon.ServerMessageID.PING_REPLY:
if (pingStopwatch.IsRunning)
{
enqueueTextMessage("Ping Reply: " + pingStopwatch.ElapsedMilliseconds + "ms");
lastPing = pingStopwatch.ElapsedMilliseconds;
pingStopwatch.Stop();
pingStopwatch.Reset();
}
break;
case KMPCommon.ServerMessageID.SYNC:
if (data != null) gameManager.targetTick = BitConverter.ToDouble(data,0) + Convert.ToDouble(lastPing);
break;
case KMPCommon.ServerMessageID.SYNC_COMPLETE:
gameManager.HandleSyncCompleted();
break;
}
}
public static void clearConnectionState()
{
try {
//Abort all threads
DebugLog("Aborting chat thread...");
safeAbort(chatThread, true);
DebugLog("Aborting connection thread...");
safeAbort(connectionThread, true);
DebugLog("Aborting interop thread...");
safeAbort(interopThread, true);
DebugLog("Aborting client thread...");
safeAbort(serverThread, true);
DebugLog("Closing connections...");
//Close the socket if it's still open
if (tcpSocket != null)
tcpSocket.Close();
tcpSocket = null;
if (udpSocket != null)
udpSocket.Close();
udpSocket = null;
}
catch (ThreadAbortException) { }
DebugLog("Disconnected");
}
static void handleChatInput(String line)
{
if (line.Length > 0)
{
if (quitHelperMessageShow && (line == "q" || line == "Q"))
{
enqueuePluginChatMessage("If you are trying to quit, use the /quit command.", true);
quitHelperMessageShow = false;
}
if (line.ElementAt(0) == '/')
{
String line_lower = line.ToLower();
if (line_lower == "/quit")
{
intentionalConnectionEnd = true;
endSession = true;
sendConnectionEndMessage("Quit");
}
else if (line_lower == "/ping")
{
if (!pingStopwatch.IsRunning)
{
sendMessageTCP(KMPCommon.ClientMessageID.PING, null);
pingStopwatch.Start();
}
}
else if (line_lower == "/debug")
{
debugging = !debugging;
enqueuePluginChatMessage("debug " + debugging);
}
else if (line_lower.Length > (KMPCommon.SHARE_CRAFT_COMMAND.Length + 1)
&& line_lower.Substring(0, KMPCommon.SHARE_CRAFT_COMMAND.Length) == KMPCommon.SHARE_CRAFT_COMMAND)
{
//Share a craft file
String craft_name = line.Substring(KMPCommon.SHARE_CRAFT_COMMAND.Length + 1);
byte craft_type = 0;
String filename = findCraftFilename(craft_name, ref craft_type);
if (filename != null && filename.Length > 0)
{
try
{
//byte[] craft_bytes = KSP.IO.File.ReadAllBytes<KMPClientMain>(filename);
byte[] craft_bytes = System.IO.File.ReadAllBytes(filename);
sendShareCraftMessage(craft_name, craft_bytes, craft_type);
}
catch
{
enqueueTextMessage("Error reading craft file: " + filename);
}
}
else
enqueueTextMessage("Craft file not found: " + craft_name);
}
}
else
{
sendTextMessage(line);
}
}
}
static void passExceptionToMain(Exception e)
{
lock (threadExceptionLock)
{
if (threadException == null)
threadException = e;
}
}
//Threads
static void handlePluginInterop()
{
try
{
while (true)
{
writeClientData();
if (handshakeCompleted)
processPluginInterop();
if (stopwatch.ElapsedMilliseconds - lastInteropWriteTime >= INTEROP_WRITE_INTERVAL)
{
if (writePluginInterop())
{
lastInteropWriteTime = stopwatch.ElapsedMilliseconds;
}
}
//Throttle the rate at which you can share screenshots
if (stopwatch.ElapsedMilliseconds - lastScreenshotShareTime > screenshotInterval)
{
lock (screenshotOutLock)
{
if (queuedOutScreenshot != null)
{
DebugLog ("screenshot");
//Share the screenshot
sendShareScreenshotMessage(queuedOutScreenshot);
lastSharedScreenshot = queuedOutScreenshot;
queuedOutScreenshot = null;
lastScreenshotShareTime = stopwatch.ElapsedMilliseconds;
//Send the screenshot back to the plugin if the player is watching themselves
if (watchPlayerName == username)
enqueueClientInteropMessage(KMPCommon.ClientInteropMessageID.SCREENSHOT_RECEIVE, lastSharedScreenshot);
DebugLog ("done screenshot");
}
}
}
Thread.Sleep(SLEEP_TIME);
}
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
DebugLog("Error in handlePluginInterop: " + e.Message);
passExceptionToMain(e);
}
}
static void handlePluginUpdates()
{
try
{
while (true)
{
writeClientData();
//readPluginUpdates();
//writeQueuedUpdates();
int sleep_time = 0;
lock (serverSettingsLock)
{
sleep_time = updateInterval;
}
Thread.Sleep(sleep_time);
}
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
passExceptionToMain(e);
}
}
static void handleConnection()
{
try
{
while (true)
{
if (pingStopwatch.IsRunning && pingStopwatch.ElapsedMilliseconds > PING_TIMEOUT_DELAY)
{
enqueueTextMessage("Ping timed out.", true);
pingStopwatch.Stop();
pingStopwatch.Reset();
}
//Send a keep-alive message to prevent timeout
if (stopwatch.ElapsedMilliseconds - lastTCPMessageSendTime >= KEEPALIVE_DELAY)
sendMessageTCP(KMPCommon.ClientMessageID.KEEPALIVE, null);
//Handle received messages
while (receivedMessageQueue.Count > 0)
{
ServerMessage message;
message = receivedMessageQueue.Dequeue();
handleMessage(message.id, message.data);
}
if (udpSocket != null && handshakeCompleted)
{
//Update the status of the udp connection
long last_udp_ack = 0;
long last_udp_send = 0;
lock (udpTimestampLock) {
last_udp_ack = lastUDPAckReceiveTime;
last_udp_send = lastUDPMessageSendTime;
}
bool udp_should_be_connected =
last_udp_ack > 0 && (stopwatch.ElapsedMilliseconds - last_udp_ack) < UDP_TIMEOUT_DELAY;
if (udpConnected != udp_should_be_connected)
{
if (udp_should_be_connected)
enqueueTextMessage("UDP connection established.", false, true);
else
enqueueTextMessage("UDP connection lost.", false, true);
udpConnected = udp_should_be_connected;
if ((stopwatch.ElapsedMilliseconds - last_udp_ack) > UDP_TIMEOUT_DELAY*10)
throw new Exception("UDP connection lost and could not be reconnected.");
}
//Send a probe message to try to establish a udp connection
if ((stopwatch.ElapsedMilliseconds - last_udp_send) > UDP_PROBE_DELAY)
sendUDPProbeMessage();
}
Thread.Sleep(SLEEP_TIME);
}
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
passExceptionToMain(e);
}
}
static void handleChat()
{
try
{
StringBuilder sb = new StringBuilder();
while (true)
{
if (sb.Length == 0)
{
//Handle incoming messages
try
{
while (textMessageQueue.Count > 0)
{
InTextMessage message;
message = textMessageQueue.Dequeue();
UnityEngine.Debug.Log(message.message);
}
}
catch (KSP.IO.IOException)
{
}
}
Thread.Sleep(SLEEP_TIME);
}
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
passExceptionToMain(e);
}
}
static void safeAbort(Thread thread, bool join = false)
{
try
{
if (thread != null)
{
thread.Abort();
if (join)
thread.Join();
}
}
catch (ThreadAbortException) { }
catch (ThreadStateException) { }
catch (ThreadInterruptedException) { }
}
//Plugin Interop
static bool writePluginInterop()
{
bool success = false;
lock (interopOutQueueLock)
{
if (interopOutQueue.Count > 0)
{
try
{
while (interopOutQueue.Count > 0)
{
byte[] message;
message = interopOutQueue.Dequeue();
KSP.IO.MemoryStream ms = new KSP.IO.MemoryStream();
ms.Write(KMPCommon.intToBytes(KMPCommon.FILE_FORMAT_VERSION), 0, 4);
ms.Write(message,0,message.Length);
gameManager.acceptClientInterop(ms.ToArray());
}
success = true;