-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAGKServer.php
More file actions
1853 lines (1529 loc) · 67.6 KB
/
AGKServer.php
File metadata and controls
1853 lines (1529 loc) · 67.6 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
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
#!/usr/bin/php -q
<?php
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//
// _____ _ __ _____
// /\ / ____| |/ / / ____|
// / \ | | __| ' / | (___ ___ _ ____ _____ _ __
// / /\ \| | |_ | < \___ \ / _ \ '__\ \ / / _ \ '__|
// / ____ \ |__| | . \ ____) | __/ | \ V / __/ |
// /_/ \_\_____|_|\_\ |_____/ \___|_| \_/ \___|_|
//
// By MikeMax
// (mikemaxfr@gmail.com)
//
//
// * AGK Server Command-line options :
// ---------------------------------
//
// Please first ! ===>> chmod +x AGKServer.php
//
// and then :
//
// ./AGKServer.php debug => Start AGKServer in debug mode (direct terminal output ... CTRL + C to stop server)
// ./AGKServer.php start => Start AGKServer as a daemon
// ./AGKServer.php stop => Stop AGKServer daemon
//
//
//
// * Available functions for Events :
// --------------------------------
//
// - onAGKClientJoin($iClientID) => Triggered when a client connects to this server
// - onAGKClientQuit($iClientID) => Triggered when a client disconnects from this server
// - onAGKClientChangeChannel($iClientID, $iOldChannelNumber, $iNewChannelNumber) => Triggered when client is joining a new channel
// - onAGKClientNetworkMessage($iSenderID, $iDestinationID, $Message) => Triggered when a client has sent a message to any client(s)
// - onAGKClientUpdateVariable($iClientID,$sVariableName,$mVariableValue) => Triggered when a client has updated a variable.
// - onAGKServerRefreshTimer() => Triggered every SERVER_REFRESH_INTERVAL nanoseconds.
//
// * Available Methods/Commands within Events :
// ------------------------------------------
//
// - writeLog($sString) => echoes $string in terminal in debug mode or in a log file (AGKServer.php.log beside the php file) in daemon mode.
//
// - GetClientName($iClientID) => (string) Retrieve name of the client
// - GetClientIP($iClientID) => (string) Retrieve client's IP Address
// - GetClientChannelNumber($iClientID) => (integer) Retrieve current client channel number
// - GetNetworkClientVariable($iClientID, $sVariableName) => (variant) Get Local variable (integer or float) from client (Respect the AGK Network ResetMode)
// - GetNetworkClientInteger($iClientID, $sVariableName) => (integer) Alias of GetNetworkClientVariable command
// - GetNetworkClientFloat($iClientID, $sVariableName) => (float) Alias of GetNetworkClientVariable command
// - SetNetworkLocalInteger($ChannelNumber, $sVariableName, $iValue [, $ResetMode = 0]) => Sets/updates a server local integer variable which will be transmitted to clients of $iChannelNumber
// - SetNetworkLocalFloat($ChannelNumber, $sVariableName, $fValue [, $ResetMode = 0]) => Sets/updates a server local float variable which will be transmitted to clients of $iChannelNumber
//
// - GetChannelClientsCount($iChannelNumber) => (integer) Retrieve number of clients in $iChannelNumber
// - GetChannelClientsList($iChannelNumber) => (array of ("ID","Name","ChannelNumber")) Retrieve Clients Names,IDs,ChannelNumber in $iChannelNumber ($iChannelNumber = -1 to retrieve ALL connected Clients with respective ChannelNumber)
// - GetChannelsList() => (array of('ChannelNumber')) => Retrieve IDs of nonempty channels
// - forceChannelJoin($PlayerID, $ChannelNumber) => Make client to join a specific channel number (warning : doesn't not update his SERVER_CHANNEL variable !)
//
// - GetNetworkMessageString($Message) => (string) Extract expected String from the message and advances the message pointer
// - GetNetworkMessageInteger($Message) => (integer) Extract expected Integer from the message and advances the message pointer
// - GetNetworkMessageFloat($Message) => (float) Extract expected Float from the message and advances the message pointer
//
// - StopPropagation() => Tell explicitely to the server to DO NOT transmit received message or variables to targetted client(s). (Very special cases)
//
// - Class NetworkMessage() => You can create one or more messages with differents data types (string, integer, float)
//
// Methods :
// ---------
//
// - AddNetworkMessageString(string) => Add a string into the message instance buffer
// - AddNetworkMessageInteger(integer) => Add an integer value into the message instance buffer
// - AddNetworkMessageFloat(float) => Add an float value into the message instance buffer
// - Send(ClientID) => Send the message to ClientID and clear the buffer (ClientID=0 to send to ALL clients connected to the server (over the Channel isolation))
// - SendChannel(ChannelNumber) => Send the message to all Clients present in ChannelNumber and clear the buffer
//
// Usage Example 1 (Usual Way) :
// -----------------------------
//
// $msg1 = new NetworkMessage(); // Can be instantiated once and be used multiple times in events to avoid recreating for each message.
//
// $msg1->AddNetworkMessageString("This is an example message for $ClientID1 with a string and integer and float");
// $msg1->AddNetworkMessageInteger(123456);
// $msg1->AddNetworkMessageFloat(123.456);
// $msg1->Send(0,$ClientID1); // Send the message and clear the buffer automatically if you want to reuse the same instance for another message
//
// $msg1->AddNetworkMessageString("This is an example message for $ClientID1 with a string and integer and float");
// $msg1->AddNetworkMessageInteger(123456);
// $msg1->AddNetworkMessageFloat(123.456);
// $msg1->Send(0,$ClientID2); // Send Message and Clear buffer...
//
//
//
// Usage Example 2 (Fluent Interface Way) :
// ----------------------------------------
//
// $msg2 = new NetworkMessage();
// $msg2->AddNetworkMessageString("This is an example message with a string and integer and float")
// ->AddNetworkMessageInteger(123456)
// ->AddNetworkMessageFloat(123.456)
// ->Send(0,$ClientID1)
// ->AddNetworkMessageString("This is another example message with a string and Float")
// ->AddNetworkMessageFloat(123456789)
// ->AddNetworkMessageFloat(123.456)
// ->Send(0,$ClientID2);
//
//
//
//* TODO :
// ------
//
// - Commands to create Virtual Client/Players (bots) and interact with.
// - Make the server able to work in a cluster (with mirrors to prevent server failures)
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/********************** CONFIGURATION **********************/
date_default_timezone_set('Europe/Paris');
define("SERVER_BIND_ADDRESS", false); // Server Address to Bind (set this to false to listen to any interface => 0.0.0.0)
define("SERVER_PORT", 9000); // Server Port the players will connect
define("SERVER_NAME", "AGKServer"); // Server Display Name for clients/players
define("SERVER_REFRESH_INTERVAL", 25000); // Server logic Timer in nanoseconds // depends on Server CPU capabilities
/********************** PLUGINS ****************************/
include "AGKServer_NetGamePlugin.php"; // We Load the NetGame Plugin ! :) all functions are prefixed by "NGP_"
/***********************************************************/
/********************** SERVER EVENTS ******************/
/***********************************************************/
function onAGKServerRefreshTimer()
{
// DO NOT writeLog anything here ! it will flood your terminal or logfile !
// Here you can check for date or time to fire messages or actions (for example).
// Be careful to use "reset" variables or flag true/false once your date/time actions are done, this event is triggered multiple times in a second (SERVER_REFRESH_INTERVAL)...
// Send the worldstate to all nonempty channels (Mandatory)
foreach (GetChannelsList() as $NonEmptyChannel) {
NGP_sendWorldState($NonEmptyChannel);
}
// Do other things ...
}
function onAGKClientJoin($iClientID)
{
// when a client Join the server (AGK Command : JoinNetwork )
// Mandatory for cleaning states in NGP Plugin and Send World Step interval configuration to client
NGP_initClient($iClientID);
// Debug
writeLog(GetClientName($iClientID) . " has joined the server ! :) (channel 0 by default)");
// 2D: Player starts to X=577,Y=628 ? :)
// NGP_SetClientState($iClientID, POS_X, 577);
// NGP_SetClientState($iClientID, POS_Y, 628);
// 3D: Player starts to X=10 Y=0 Z=10
NGP_SetClientState($iClientID, POS_X, 10);
NGP_SetClientState($iClientID, POS_Y, 0);
NGP_SetClientState($iClientID, POS_Z, 10);
}
function onAGKClientChangeChannel($iClientID, $iOldChannelNumber, $iNewChannelNumber)
{
// when a client move from a channel to another ( AGK Command : SetNetworkLocalInteger( networkId, "SERVER_CHANNEL", channelNumber) )
writeLog(GetClientName($iClientID) . " has joined channel number " . $iNewChannelNumber . " (was previously on channel number " . $iOldChannelNumber . ") ! ");
writeLog("Channel Number " . $iNewChannelNumber . " / Actual clients count : " . GetChannelClientsCount($iNewChannelNumber));
// Display the clients list of $newChannelNumber in log file
// writeLog(print_r(GetChannelClientsList($iNewChannelNumber), true));
// Display non-empty channels numbers
// writeLog(print_r(GetChannelsList(), true));
// Display coordinates of a client
// writeLog(print_r(NGP_GetClientState($iClientID), true));
// forceChannelJoin($iClientID, 25);
}
function onAGKClientQuit($iClientID, $QuitMessage)
{
// when a client quits the server (AGK Command : CloseNetwork )
writeLog(GetClientName($iClientID) . " has quit the server ! :( => " . $QuitMessage);
NGP_destroyClient($iClientID); // Free The client state variables (Mandatory)
}
function onAGKClientUpdateVariable($iClientID, $sVariableName, $mVariableValue)
{
// when a client change his local variable (AGK Commands : SetNetworkLocalFloat or SetNetworkLocalInteger)
writeLog(GetClientName($iClientID) . "VAR" . $sVariableName . " => " . $mVariableValue);
// DO NOT writeLog anything here ! it will flood your terminal or logfile if variables are changing constantly !
}
function onAGKClientNetworkMessage($iSenderID, $iDestinationID, $Message)
{
// when a client (SenderID) send a NetworkMessage (AGK Command SendNetworkMessage)
// Forward Message to the NetGamePlugin to check for Clients Movements Messages and update internal WorldState (Mandatory)
NGP_CheckForReceivedMovements($iSenderID, $iDestinationID, $Message);
// Do other things...
$iCommand = GetNetworkMessageInteger($Message);
if ($iCommand == 6800) {
// Arbitraty command 6800 for Chat Messages
// ChatBox Message Interception and display in Logs
writeLog(GetClientName($iSenderID) . " : " . GetNetworkMessageString($Message));
// Stop propagation of the message to the tzrgetted clients ? No ! ...
// StopPropagation();
}
}
define("SERVER_DEBUG", false); // Display server Debug informations (true/false)
define("MAX_PING_TIMEOUT_SECONDS", 15); // Over MAX_PING_TIMEOUT_SECONDS Seconds, consider Client as TimeOuted
/*****************************************************************************
*****************************************************************************
*****************************************************************************
********************* *************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
*************************** *******************************
********************* *************************
*****************************************************************************
*****************************************************************************
*****************************************************************************/
set_time_limit(0); // no limit
// Then, specify on what IP address and ports to listen for use later in
// initializing the class. It is easier to do this in one section reserved
// for global script settings.
// It's not a bad idea to initialize the class early so you don't try to
// referrence it before it's created accidentily.
$AGKSocket = new floSocket(SERVER_BIND_ADDRESS, SERVER_PORT, SERVER_REFRESH_INTERVAL);
// We don't want this to timeout on us, we want to use our own timeout system.
// For this example, 60 seconds should be sufficient.
//$AGKSocket->set_timeout(60);
/*
You may also want to set the max_execution_time directive in your php.ini file
if you are running in safe mode and you want to run your script indefinitely.
Additionally, your webserver can have other timeouts. E.g. Apache has Timeout
directive, IIS has CGI timeout function, both default to 300 seconds. See the
webserver documentation for meaning of it.
*/
$_AGK_Players = array();
$_AGK_Players_PingState = array();
$_AGK_PlayersIP = array();
$_AGK_PlayersVariables = array();
$_AGK_ServerVariables = array();
$_AGK_subChannel = array();
$StopPropagation = false;
// Let's assign some event capturing functions.
// In the event fired by a new connection, one variable is passed (in this case
// named $channel) which contains an integer index of the floSocket channel
// referrence.
function _agk_new_connection($channel)
{
// We have to reference $AGKSocket because it is not local in this
// function and we are planning on using it in this example.
global $AGKSocket, $_AGK_PlayersIP, $_AGK_Players_PingState;
$_AGK_Players_PingState[$channel] = time();
// Like I said, we are going to use it. get_remote_address and
// get_remote_port are pretty straight forward functions.
$remote_address = $AGKSocket->get_remote_address($channel);
$report_port = $AGKSocket->get_remote_port($channel);
$_AGK_PlayersIP[$channel] = $remote_address;
// Simple echo lets us know at our console someone connected.
if (SERVER_DEBUG) {
writeLog("New connection ($channel) from $remote_address on port $report_port" . PHP_EOL);
}
}
// The event fired by new data passes the channel as well as the current buffer
// one byte at a time.
function _agk_data_received($channel, $buffer)
{
global $AGKSocket;
_AGK_HandleReceivedData($channel, $buffer);
/*
if ($buffer == chr(27)) {
if (SERVER_DEBUG) {
writeLog("STOPPING SERVER!!! ESC DETECTED");
}
$AGKSocket->stop("Server stopped by ESC detection.");
}
// Or, you can just close the one connection, here with "q" (or "Q").
if ($buffer == "q" || $buffer == "Q") {
$AGKSocket->close($channel, "Channel closed by Q detection.");
}
*/
}
function _AGK_HandleReceivedData($channel, $buffer)
{
global $AGKSocket, $_AGK_Players, $_AGK_PlayersVariables, $_AGK_subChannel, $StopPropagation, $_AGK_Players_PingState;
// DEBUG
if (SERVER_DEBUG) {
writeLog("-----------BEGIN Global Data (" . $channel . " / length: " . strlen($buffer) . ") -----------");
$tmpLog = "";
for ($i = 0; $i <= strlen($buffer) - 1; $i++) {
$tmpLog .= ord($buffer[$i]) . " ";
}
writeLog($tmpLog);
writeLog("-----------END Global Message-----------");
// END DEBUG
}
//writeLog(strlen($buffer) . " octects");
//////////////////////////////////////// NEW CLIENT JOINS /////////////////////////////////////////////////////////////
if (!isset($_AGK_Players[$channel])) {
$ClientNameLength = bin2int(substr($buffer, 0, 4));
$ClientName = substr($buffer, 4, $ClientNameLength);
if (SERVER_DEBUG) {
writeLog("Client " . $ClientName . " has just joined channel " . $channel);
}
$AGKSocket->write($channel, int2bin(1));
///////////// PLAYERS NAMES
// CountPlayer+le serveur+le nouveau = +2 ( celui qui vient de se connecter)
$newPlayerID = $channel + 2;
// $ClientName = trim($buffer);
$AGKSocket->write($channel, int2bin($newPlayerID));
// CountPlayer avant celui la (+1 pour le serveur)
$nbMainRoomPlayers = 0;
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($_AGK_subChannel[$PlayerChannel] == 0) {
$nbMainRoomPlayers++;
}
}
$AGKSocket->write($channel, int2bin(($nbMainRoomPlayers + 1)));
// Number 1 => The Server
/////////////////////////////////////
// Trame de variables serveur
$ServerVars = _AGK_sendServerNetworkAllVariables(0, $channel, 1);
// Trame Numero du serveur (toujours 1) + variables
$AGKSocket->write($channel, int2bin(1) . int2bin(strlen(SERVER_NAME)) . SERVER_NAME . int2bin($ServerVars['CountVars']) . $ServerVars['Vars']);
//$AGKSocket->write($channel, $ServerVars['CountVars'] . $ServerVars['Vars']);
// Send the Clients List to the new client
///////////////////////////////////////////
// $NumPlayer = 2;
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($_AGK_subChannel[$PlayerChannel] != 0) {
continue;
}
// Trame de variables client
$ClientVars = _AGK_sendNetworkAllVariables($PlayerChannel, $channel, 1);
// Trame declaration joueur existant + variables
$AGKSocket->write($channel, int2bin($PlayerChannel + 2) . int2bin(strlen($PlayerName)) . $PlayerName . int2bin($ClientVars['CountVars']) . $ClientVars['Vars']);
}
// Notify Other Clients of the join (MSGID 1 )
/////////////////////////////////////////////
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
// If Users are not in the main channel, => continue
if ($_AGK_subChannel[$PlayerChannel] != 0) {
continue;
}
// Alert client
//$AGKSocket->write($PlayerChannel, chr(1).chr(00).chr(00).chr(00));
$AGKSocket->write($PlayerChannel, int2bin(1) . int2bin($newPlayerID) . int2bin(strlen($ClientName)) . $ClientName);
}
// Enregistrement du nouveau joueur
$_AGK_Players[$channel] = $ClientName;
$_AGK_subChannel[$channel] = 0;
if (SERVER_DEBUG) {
writeLog("<= Player Joined : " . $ClientName);
}
onAGKClientJoin($newPlayerID);
onAGKClientChangeChannel($channel + 2, 0, 0);
return (1);
}
//////////////////////////////////////////////////////////////////// COMMANDS ///////////////////////////////////////////////////////
//while (strlen($buffer) > 0) {
// Consommer le buffer !
$AGKCommand = bin2int(substr($buffer, 0, 4));
//$AGKCommand = $AGKCommand[1];
//writeLog("--------\nAGK Command : " . $AGKCommand . "\n-------------");
// New variables
if ($AGKCommand == 2) {
// (2) (NB Variable) [(VariableName Length) (Variable Name) (reset = 0/1) (Integer =0 / Float = 1) (Value)]
// DEBUG
if (SERVER_DEBUG) {
writeLog("-----------BEGIN Unit New Variable-----------");
$tmpLog = "";
for ($i = 0; $i <= strlen($buffer) - 1; $i++) {
$tmpLog .= ord($buffer[$i]) . " ";
}
writeLog($tmpLog);
writeLog("-----------END Unit New Variable-----------");
}
$bkpBuffer = $buffer;
/// On stock les variables en local pour utilisation ultérieure.
$Variable = array();
$NBVariable = bin2int(substr($buffer, 4, 4));
$NoVariable = 0;
$buffer = substr($buffer, 8);
while (strlen($buffer) > 0) {
$NoVariable++;
if ($NoVariable > $NBVariable) {
break;
}
$VariableNameLength = bin2int(substr($buffer, 0, 4));
//if (strlen($buffer) < (4 + $VariableNameLength + 4 + 4 + 4)) {
// writeLog("Message Breaks !!!");
//}
$Variable["Name"] = substr($buffer, 4, $VariableNameLength);
$Variable["Reset"] = bin2int(substr($buffer, (4 + $VariableNameLength), 4)); // 0 : no reset / 1 : reset
$Variable["Type"] = bin2int(substr($buffer, 4 + $VariableNameLength + 4, 4)); // 0 : integer / 1 : Float
if ($Variable["Type"] == 0) {
$Variable["Value"] = bin2uint(substr($buffer, 4 + $VariableNameLength + 4 + 4, 4));
} elseif ($Variable["Type"] == 1) {
$Variable["Value"] = bin2float(substr($buffer, 4 + $VariableNameLength + 4 + 4, 4));
}
$Variable["ServerValue"] = $Variable["Value"];
$StopPropagation = false;
onAGKClientUpdateVariable($channel + 2, $Variable["Name"], $Variable["Value"]);
$_AGK_PlayersVariables[$channel][] = $Variable;
if (SERVER_DEBUG) {
writeLog("<= NewVariable (" . $_AGK_Players[$channel] . ") : " . $Variable['Name']);
}
if ($Variable["Name"] == "SERVER_CHANNEL" && $_AGK_subChannel[$channel] != $Variable["Value"]) {
$previousChannel = $_AGK_subChannel[$channel];
$_AGK_subChannel[$channel] = $Variable["Value"];
_AGK_notifyNewChannelToUser($channel, $previousChannel, $_AGK_subChannel[$channel]);
}
$buffer = substr($buffer, 4 + $VariableNameLength + 4 + 4 + 4);
}
if (!$StopPropagation) {
// On termine par transmettre la/les nouvelles variables aux autres clients
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($PlayerChannel == $channel || $_AGK_subChannel[$channel] != $_AGK_subChannel[$PlayerChannel]) {
continue;
}
$AGKSocket->write($PlayerChannel, int2bin(2) . int2bin($channel + 2) . substr($bkpBuffer, 4, strlen($bkpBuffer) - 4 - strlen($buffer)));
}
}
if (strlen($buffer) > 0) {
// Si il reste du buffer, on continue le traitement
_AGK_HandleReceivedData($channel, $buffer);
return (1);
}
// var_dump($_AGK_PlayersVariables);
}
if ($AGKCommand == 3) {
// (3) (NB Variable) [(IndexVariable) (Value)]
// DEBUG
if (SERVER_DEBUG) {
writeLog("-----------BEGIN Unit Updated Variable-----------");
$tmpLog = "";
for ($i = 0; $i <= strlen($buffer) - 1; $i++) {
$tmpLog .= ord($buffer[$i]) . " ";
}
writeLog($tmpLog);
writeLog("-----------END Unit Updated Variable-----------");
}
$bkpBuffer = $buffer;
// On met à jour les variables
/// On stock les variables en local pour utilisation ultérieure.
$Variable = array();
$NBVariable = bin2int(substr($buffer, 4, 4));
$NoVariable = 0;
$buffer = substr($buffer, 8);
while (strlen($buffer) > 0) {
$NoVariable++;
if ($NoVariable > $NBVariable) {
break;
}
$VariableIndex = bin2int(substr($buffer, 0, 4));
if ($_AGK_PlayersVariables[$channel][$VariableIndex]["Type"] == 0) {
$_AGK_PlayersVariables[$channel][$VariableIndex]["Value"] = bin2uint(substr($buffer, 4, 4));
} elseif ($_AGK_PlayersVariables[$channel][$VariableIndex]["Type"] == 1) {
$_AGK_PlayersVariables[$channel][$VariableIndex]["Value"] = bin2float(substr($buffer, 4, 4));
}
$_AGK_PlayersVariables[$channel][$VariableIndex]["ServerValue"] = $_AGK_PlayersVariables[$channel][$VariableIndex]["Value"];
$StopPropagation = false;
onAGKClientUpdateVariable($channel + 2, $_AGK_PlayersVariables[$channel][$VariableIndex]["Name"], $_AGK_PlayersVariables[$channel][$VariableIndex]["Value"]);
if (SERVER_DEBUG) {
writeLog("<= UpdateVariable (" . $_AGK_Players[$channel] . ") : " . $_AGK_PlayersVariables[$channel][$VariableIndex]['Name']);
}
if ($_AGK_PlayersVariables[$channel][$VariableIndex]["Name"] == "SERVER_CHANNEL" && $_AGK_subChannel[$channel] != $_AGK_PlayersVariables[$channel][$VariableIndex]["Value"]) {
$previousChannel = $_AGK_subChannel[$channel];
$_AGK_subChannel[$channel] = $_AGK_PlayersVariables[$channel][$VariableIndex]["Value"];
_AGK_notifyNewChannelToUser($channel, $previousChannel, $_AGK_subChannel[$channel]);
}
$buffer = substr($buffer, 8);
}
if (!$StopPropagation) {
// On transmet la/les nouvelles variables aux autres clients
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($PlayerChannel == $channel || $_AGK_subChannel[$channel] != $_AGK_subChannel[$PlayerChannel]) {
continue;
}
$AGKSocket->write($PlayerChannel, int2bin(3) . int2bin($channel + 2) . substr($bkpBuffer, 4, strlen($bkpBuffer) - 4 - strlen($buffer)));
}
}
if (strlen($buffer) > 0) {
// Si il reste du buffer, on continue le traitement
_AGK_HandleReceivedData($channel, $buffer);
return (1);
}
// var_dump($_AGK_PlayersVariables);
}
/////// Network Message
if ($AGKCommand == 5) {
while (substr($buffer, 0, 4) == int2bin(5)) {
//$DataChunk = substr( $DataChunk, 4 );
$ClientID = bin2int(substr($buffer, 4, 4));
$DestID = bin2int(substr($buffer, 8, 4));
$MsgLength = bin2int(substr($buffer, 12, 4));
$IncomingMessage = substr($buffer, 16);
// DEBUG
if (SERVER_DEBUG) {
writeLog("-----------BEGIN Unit Message-----------");
$tmpLog = "";
for ($i = 0; $i <= strlen($IncomingMessage) - 1; $i++) {
$tmpLog .= ord($IncomingMessage[$i]) . " ";
}
writeLog($tmpLog);
writeLog("-----------END Unit Message-----------");
}
// Callback d'evenement d'arrivée d'un message
$StopPropagation = false;
onAGKClientNetworkMessage($ClientID, $DestID, $IncomingMessage);
if (!$StopPropagation) {
//echo "forward";
// Forward du message
if ($DestID == 0) {
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($PlayerChannel == $channel || $_AGK_subChannel[$channel] != $_AGK_subChannel[$PlayerChannel]) {
continue;
}
$AGKSocket->write($PlayerChannel, int2bin(5) . int2bin($ClientID) . substr($buffer, 12, 4 + $MsgLength));
}
} else {
if ($DestID != 1) {
// Si le destinataire n'est pas le serveur
if ($_AGK_subChannel[$channel] == $_AGK_subChannel[$DestID - 2]) {
// Si le destinataire se trouve sur le meme serveur que l'expediteur
$AGKSocket->write($DestID - 2, int2bin(5) . int2bin($ClientID) . substr($buffer, 12, 4 + $MsgLength));
}
}
}
}
//parseData($data = $IncomingMessage, false);
$buffer = substr($buffer, 16 + $MsgLength);
}
if (strlen($buffer) > 0) {
// Si il reste du buffer, on continue le traitement
_AGK_HandleReceivedData($channel, $buffer);
return (1);
}
//return (1);
}
/////// Check Connection / (KeepAlive) <= CMD 7
if ($AGKCommand == 7) {
if (SERVER_DEBUG) {
//writeLog("<= PING REQUEST " . $_AGK_Players[$channel]);
// Answer to client ( => CMD 6)
//writeLog("=> PING RESPONSE");
}
$_AGK_Players_PingState[$channel] = time();
$AGKSocket->write($channel, int2bin(6));
$buffer = substr($buffer, 4);
if (strlen($buffer) > 0) {
// Si il reste du buffer, on continue le traitement
_AGK_HandleReceivedData($channel, $buffer);
return (1);
}
//return (1);
}
//}
}
function _AGK_notifyNewChannelToUser($channel, $oldChannelNumber, $newChannelNumber)
{
global $AGKSocket, $_AGK_Players, $_AGK_subChannel;
//echo $_AGK_Players[$channel] . " is changeing from channel " . $oldChannelNumber . " to " . $newChannelNumber . PHP_EOL;
// Notify the user of the virtual QUIT message of the user no longer in the same room
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($PlayerChannel == $channel) {
continue;
}
if ($_AGK_subChannel[$PlayerChannel] == $oldChannelNumber) {
//Notify the user of the quit of others clients
//echo "notify " . $PlayerName . " of the quitting of " . $_AGK_Players[$channel] . " on channel " . $oldChannelNumber . PHP_EOL;
$AGKSocket->write($channel, int2bin(4) . int2bin($PlayerChannel + 2));
//Notify others clients of the quit of the current client
$AGKSocket->write($PlayerChannel, int2bin(4) . int2bin($channel + 2));
}
}
// Notify the user of the virtual JOIN messages of the users in the same new room
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($PlayerChannel == $channel) {
continue;
}
if ($_AGK_subChannel[$PlayerChannel] == $newChannelNumber) {
//echo "notify new arrivant " . $_AGK_Players[$channel] . "(" . $channel . ") of the virtual joining of " . $PlayerName . "(" . $PlayerChannel . ")" . PHP_EOL;
// notify the current client of the join of the others already in the room
$AGKSocket->write($channel, int2bin(1) . int2bin($PlayerChannel + 2) . int2bin(strlen($PlayerName)) . $PlayerName);
// Boucle sur les variable du $PlayerChannel pour l'envoyer au nouveau venu
_AGK_sendNetworkAllVariables($PlayerChannel, $channel);
//echo "notify " . $PlayerName . "(" . $PlayerChannel . ") of the joiningggg of " . $_AGK_Players[$channel] . "(" . $channel . ")" . PHP_EOL;
// notify others clients already in the room of the join of this users
$AGKSocket->write($PlayerChannel, int2bin(1) . int2bin($channel + 2) . int2bin(strlen($_AGK_Players[$channel])) . $_AGK_Players[$channel]);
// Boucle sur les variable du $channel pour l'envoyer aux users déjà en room
_AGK_sendNetworkAllVariables($channel, $PlayerChannel);
//$AGKSocket->write($PlayerChannel, int2bin(0));
// Send Server Variable of the new channel to the new Client of this room
_AGK_sendServerNetworkAllVariables($newChannelNumber, $channel);
}
}
onAGKClientChangeChannel($channel + 2, $oldChannelNumber, $newChannelNumber);
}
function _AGK_sendNetworkAllVariables($fromChannel, $toChannel, $returnBinary = 0)
{
global $AGKSocket, $_AGK_PlayersVariables, $_AGK_Players;
//echo "nb variables:" . count($_AGK_PlayersVariables[$fromChannel]) . PHP_EOL;
if (count($_AGK_PlayersVariables[$fromChannel]) > 0) {
$binHeadVarMsg = int2bin(2) . int2bin($fromChannel + 2) . int2bin(count($_AGK_PlayersVariables[$fromChannel]));
$binVarMsg = "";
foreach ($_AGK_PlayersVariables[$fromChannel] as $indexVariable => $Variable) {
//echo "variable envoyée à " . $_AGK_Players[$toChannel] . ": " . $Variable['Name'] . PHP_EOL;
if ($returnBinary == 0) {
$binVarMsg .= int2bin(strlen($Variable['Name'])) . $Variable['Name'] . int2bin($Variable['Reset']) . int2bin($Variable['Type']);
} else {
$binVarMsg .= int2bin(strlen($Variable['Name'])) . $Variable['Name'] . int2bin($Variable['Type']) . int2bin($Variable['Reset']);
}
if ($Variable["Type"] == 0) {
$binVarMsg .= uint2bin($Variable["Value"]);
} elseif ($Variable["Type"] == 1) {
$binVarMsg .= float2bin($Variable["Value"]);
}
}
if ($returnBinary == 0) {
$AGKSocket->write($toChannel, $binHeadVarMsg . $binVarMsg);
} else {
return array("CountVars" => count($_AGK_PlayersVariables[$fromChannel]), "Vars" => $binVarMsg);
}
}
}
function _AGK_sendServerNetworkAllVariables($ChannelNumber, $toChannel, $returnBinary = 0)
{
global $AGKSocket, $_AGK_ServerVariables, $_AGK_Players;
//echo "nb variables:" . count($_AGK_PlayersVariables[$fromChannel]) . PHP_EOL;
if (!empty($_AGK_ServerVariables[$ChannelNumber]) > 0) {
$binHeadVarMsg = int2bin(2) . int2bin(1) . int2bin(count($_AGK_ServerVariables[$ChannelNumber]));
$binVarMsg = "";
foreach ($_AGK_ServerVariables[$ChannelNumber] as $indexVariable => $Variable) {
//echo "variable envoyée à " . $_AGK_Players[$toChannel] . ": " . $Variable['Name'] . PHP_EOL;
if ($returnBinary == 0) {
$binVarMsg .= int2bin(strlen($Variable['Name'])) . $Variable['Name'] . int2bin($Variable['Reset']) . int2bin($Variable['Type']);
} else {
$binVarMsg .= int2bin(strlen($Variable['Name'])) . $Variable['Name'] . int2bin($Variable['Type']) . int2bin($Variable['Reset']);
}
if ($Variable["Type"] == 0) {
$binVarMsg .= uint2bin($Variable["Value"]);
} elseif ($Variable["Type"] == 1) {
$binVarMsg .= float2bin($Variable["Value"]);
}
}
if ($returnBinary == 0) {
$AGKSocket->write($toChannel, $binHeadVarMsg . $binVarMsg);
} else {
return array("CountVars" => count($_AGK_ServerVariables[$ChannelNumber]), "Vars" => $binVarMsg);
}
}
}
/*
tick's event
*/
$LastClientsPingCheck = time();
function _agk_tick()
{
global $AGKSocket;
global $LastClientsPingCheck;
global $_AGK_Players_PingState;
global $_AGK_Players;
// Event after check buffer
//return 1;
//if (isset($_AGK_Players[$channel])) // une fois que le player est authentifié
//{
//@SendString($channel,-1,"SUPERMEGATROP COOL");
//}
if (time() - $LastClientsPingCheck > 15) {
// Check Clients every 15 seconds
//writeLog("Check Clients Ping");
$LastClientsPingCheck = time();
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
if ($LastClientsPingCheck - $_AGK_Players_PingState[$PlayerChannel] > MAX_PING_TIMEOUT_SECONDS) {
$AGKSocket->close($PlayerChannel, "Ping Timeout !");
}
}
}
//system("clear");
//var_dump($_AGK_Players);
//echo time() . PHP_EOL;
onAGKServerRefreshTimer();
}
/*
Connection lost's event
*/
function _agk_connection_lost($channel, $error, $reason)
{
global $_AGK_Players, $AGKSocket, $_AGK_PlayersVariables, $_AGK_subChannel, $_AGK_PlayersIP;
if (SERVER_DEBUG) {
writeLog("Connection lost (" . $_AGK_Players[$channel] . "): $error / " . $reason);
}
onAGKClientQuit($channel + 2, $reason);
unset($_AGK_Players[$channel]);
unset($_AGK_PlayersVariables[$channel]);
unset($_AGK_PlayersIP[$channel]);
unset($_AGK_subChannel[$channel]);
// Notify Other Clients of the quit (MSGID 4 )
/////////////////////////////////////////////
foreach ($_AGK_Players as $PlayerChannel => $PlayerName) {
//echo "alerting $PlayerName";
// Alert client
// Network Command 4
$AGKSocket->write($PlayerChannel, int2bin(4) . int2bin($channel + 2));
}
//_agk_tick($channel);
}
/*
events declaration
*/
/*
$AGKSocket->set_handler(SOCKET_EVENT_CREATED, "_agk_new_connection");
$AGKSocket->set_handler(SOCKET_EVENT_NEWDATA, "_agk_data_received");
$AGKSocket->set_handler(SOCKET_EVENT_EXPIREY, "_agk_connection_lost");
$AGKSocket->set_handler(SOCKET_EVENT_TICKERS, "_agk_tick");
*/
$ARGS = parseArgs($argv);
//var_dump($ARGS);
//exit;
if (empty(@$ARGS)) // Direct mode (no daemon)
{
echo "\n****************\n** AGK Server **\n****************\n\nArguments are : start, stop, direct\n---------------\n\n" .
basename($_SERVER["argv"][0]) . " start " . chr(9) . "Start the AGK Server Daemon\n" .
basename($_SERVER["argv"][0]) . " stop " . chr(9) . "Stop the AGK Server Daemon\n" .
basename($_SERVER["argv"][0]) . " debug " . chr(9) . "Start the AGK Server in \"Direct / Debug Mode\" (no Daemon => CTRL+C to stop)\n";
exit;
}
if (@$ARGS[0] == "stop") // (stop daemon)
{
//echo "---------------------------------------------" . PHP_EOL . "| AGK Server \"" . SERVER_NAME . "\" : Started." . PHP_EOL . "| Listening for connections on port " . SERVER_PORT . "..." . PHP_EOL . "---------------------------------------------" . PHP_EOL;
//$AGKSocket->start();
exec("killall -9 " . basename($_SERVER["argv"][0]), $output, $return);
exit(0);
}
//echo basename($_SERVER["argv"][0]);
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
exec("pgrep -f " . basename($_SERVER["argv"][0]), $output, $return);
//var_dump($output);
if (count($output) > 2) {
die("Process " . basename($_SERVER["argv"][0]) . " (" . $output[0] . ") is already running\n");
}
}
if (@$ARGS[0] == "debug") // Direct mode (no daemon)
{
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE | ~E_STRICT);
ini_set('display_errors', true);
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
system("clear");
}
writeLog("------------------------------------------------------------");
writeLog("| AGK Server \"" . SERVER_NAME . "\" : Started.");
writeLog("| Listening for connections on port " . SERVER_PORT . "...");
writeLog("| Global Server Refresh Interval : " . SERVER_REFRESH_INTERVAL . "ns ...");
if (defined("NETGAMEPLUGIN_WORLDSTATE_INTERVAL")) {
writeLog("| NetGamePlugin WorldState Broadcast Interval : " . NETGAMEPLUGIN_WORLDSTATE_INTERVAL . "ns ...");
}
writeLog("------------------------------------------------------------");
$AGKSocket->start();
exit(0);
}
function writeLog($string)
{
global $ARGS, $myDaemon;
if (@$ARGS[0] == "debug") // Direct mode (no daemon)
{
echo date("d/m/Y H:i:s") . " -> " . $string . PHP_EOL;
} else {
$myDaemon->writeLog($string);
}
}
/////////////////////// DAEMON ///////////////////////////////////
function sig_handler($signal)
{
global $myDaemon, $AGKSocket;
switch ($signal) {
case SIGTERM:
case SIGHKILL:
$AGKSocket->closeAll();
$myDaemon->writeLog("ShutDown asked");
$myDaemon->shutdown();
exit(0);
break;
case SIGHUP:
break;
}
}
function start()
{
global $AGKSocket, $myDaemon;
$myDaemon->writeLog("AGK Server \"" . SERVER_NAME . "\" : Started.");
$myDaemon->writeLog("Listening for connections on port " . SERVER_PORT . "...");
$myDaemon->writeLog("Refresh interval : " . SERVER_REFRESH_INTERVAL . "ns ...");
if (defined("NETGAMEPLUGIN_WORLDSTATE_INTERVAL")) {
writeLog("NetGamePlugin WorldState Broadcast Interval : " . NETGAMEPLUGIN_WORLDSTATE_INTERVAL . "ns ...");
}
$AGKSocket->start();
}
if (@$ARGS[0] == "start") // Direct mode (no daemon)
{
error_reporting(0);
$myDaemon = new clsDaemonize(); // Creates an instance of clsDaemonize
$myDaemon->setup_sighandler(SIGTERM, "sig_handler"); // Sets various signal handlers
$myDaemon->setup_sighandler(SIGHUP, "sig_handler");
//$myDaemon->setup_sighandler(SIGHKILL, "sig_handler");
$myDaemon->fork("start");
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////// INTERNAL LIBRARIES / FUNCTIONS ////////////////////////////////////
function bin2int($data)