/
castleclientserver.pas
802 lines (696 loc) · 23.9 KB
/
castleclientserver.pas
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
{
Copyright 2018-2024 Benedikt Magnus, Michalis Kamburelis.
This file is part of "Castle Game Engine".
"Castle Game Engine" is free software; see the file COPYING.txt,
included in this distribution, for details about the copyright.
"Castle Game Engine" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------
}
{ Client and server for network communication using TCP (TCastleTCPClient, TCastleTCPServer).
Use this in your games for easy client/server communication.
See https://castle-engine.io/manual_network.php#section_multi_player .
On Android, it requires adding
@url(https://castle-engine.io/android-Services
client_server service in your project).
On other platforms, it requires having @url(http://www.indyproject.org/ Indy) available. }
unit CastleClientServer;
{$I castleconf.inc}
interface
uses
Classes, SysUtils, Generics.Collections,
{$ifdef ANDROID}
CastleMessaging, CastleStringUtils
{$else}
IdTCPServer, IdTCPClient, IdContext, IdSocketHandle, IdGlobal
{$endif};
type
TClientConnection = record
private
{$ifndef ANDROID}
Context: TIdContext;
{$else}
ID: String;
{$endif}
public
constructor Create({$ifdef ANDROID}AID: String{$else}AContext: TIdContext{$endif});
end;
TProcedureObject = procedure of object;
TConnectionEvent = procedure of object;
TClientConnectionEvent = procedure(AClientConnection: TClientConnection) of object;
TMessageReceivedEvent = procedure(const AMessage: String) of object;
TClientMessageReceivedEvent = procedure(const AMessage: String; AClientConnection: TClientConnection) of object;
TSynchronisedStringList = {$ifdef FPC}specialize{$endif} TThreadList<String>;
{$ifndef ANDROID}
type
TMessageClientRecord = record
Message: String;
Client: TClientConnection;
end;
TMessageClientList = {$ifdef FPC}specialize{$endif} TThreadList<TMessageClientRecord>;
TClientContextList = {$ifdef FPC}specialize{$endif} TThreadList<TIdContext>; //Because Indys version isn't generic in FPC.
{$endif}
{$ifndef ANDROID}
type
TThreadSynchronisationHandler = class
protected
class var IsInitialised: Boolean;
class procedure Update(Sender: TObject);
public
class procedure Initialise;
end;
{$endif}
{$ifdef ANDROID}
type
TConnectedDictionary = specialize TDictionary<String, Boolean>;
TAndroidTCPConnectionService = class
strict protected
const AndroidServiceName = 'client-server';
strict protected
FMessageReceived: TClientMessageReceivedEvent;
FOnConnected: TClientConnectionEvent;
FOnDisconnected: TClientConnectionEvent;
FConnectedDictionary: TConnectedDictionary;
FKey: String;
FIsActive: Boolean;
function MessageFilter(const Received: TCastleStringList;
const ReceivedStream: TMemoryStream): Boolean;
public
constructor Create;
destructor Destroy; override;
public
procedure CreateServer(const APort: Word);
procedure CreateClient(const AHost: String; const APort: Word);
procedure SendMessage(const AMessage: String); overload;
procedure SendMessage(const AMessage: String; AClient: TClientConnection); overload;
procedure Close; overload;
procedure Close(AClient: TClientConnection); overload;
public
property OnConnected: TClientConnectionEvent write FOnConnected;
property OnDisconnected: TClientConnectionEvent write FOnDisconnected;
property OnMessageReceived: TClientMessageReceivedEvent write FMessageReceived;
{$ifdef FPC} property OnMessageRecieved: TClientMessageReceivedEvent write FMessageReceived; deprecated 'use OnMessageReceived'; {$endif}
public
function IsConnected: Boolean; overload;
function IsConnected(AClient: TClientConnection): Boolean; overload;
end;
{$else}
type
TCastleTCPClientThread = class(TThread)
strict protected
FClient: TIdTCPClient;
FOnConnected: TProcedureObject;
FOnDisconnected: TProcedureObject;
FOnMessageReceived: TProcedureObject;
strict protected
FMessageList: TSynchronisedStringList;
protected
procedure Execute; override;
public
constructor Create(const AClient: TIdTCPClient; const AOnMessageReceived, AOnConnected, AOnDisconnected: TProcedureObject); virtual;
destructor Destroy; override;
public
FreeClientOnTerminate: Boolean;
property MessageList: TSynchronisedStringList read FMessageList;
end;
{$endif}
type
TCastleSocket = class
strict protected
{$ifdef ANDROID}
FTCPConnectionService: TAndroidTCPConnectionService;
{$endif}
FPort: Word;
public
property Port: Word read FPort write FPort;
public
constructor Create; virtual;
destructor Destroy; override;
end;
TCastleTCPServer = class(TCastleSocket)
strict protected
{$ifndef ANDROID}
FServer: TIdTCPServer;
FClientConnectedList: TClientContextList; //Temporary list for all NEW connected clients.
FClientDisconnectedList: TClientContextList; //Same for all disconnected clients.
FClientConnectionsList: TClientContextList; //List for all CURRENTLY connected clients.
FMessageList: TMessageClientList;
procedure ServerOnConnect(AContext: TIdContext);
procedure ServerOnDisconnect(AContext: TIdContext);
procedure ServerOnExecute(AContext: TIdContext);
procedure ServerOnClientConnected;
procedure ServerOnClientDisconnected;
procedure ServerOnMessageReceived;
{$endif}
strict protected
FOnConnected: TClientConnectionEvent;
FOnDisconnected: TClientConnectionEvent;
FOnMessageReceived: TClientMessageReceivedEvent;
public
constructor Create; override;
destructor Destroy; override;
public
procedure Start; virtual;
procedure Stop; virtual;
procedure Disconnect(AClient: TClientConnection); virtual;
procedure SendToClient(const AMessage: String; AClient: TClientConnection); virtual;
procedure SendToAll(const AMessage: String); virtual;
public
function IsConnected: Boolean; overload; virtual;
function IsConnected(AClient: TClientConnection): Boolean; overload; virtual;
public
property OnConnected: TClientConnectionEvent read FOnConnected write FOnConnected;
property OnDisconnected: TClientConnectionEvent read FOnDisconnected write FOnDisconnected;
property OnMessageReceived: TClientMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived;
{$ifdef FPC} property OnMessageRecieved: TClientMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; deprecated 'use OnMessageReceived'; {$endif}
end;
TCastleTCPClient = class(TCastleSocket)
strict protected
FHostname: String;
{$ifdef ANDROID}
procedure ClientOnClientConnected(AClientConnection: TClientConnection);
procedure ClientOnClientDisconnected(AClientConnection: TClientConnection);
procedure ClientOnMessageReceived(const AMessage: String; AClientConnection: TClientConnection);
{$else}
FClient: TIdTCPClient;
FClientThread: TCastleTCPClientThread;
procedure ClientOnMessageReceived;
{$endif}
strict protected
FOnConnected: TConnectionEvent;
FOnDisconnected: TConnectionEvent;
FOnMessageReceived: TMessageReceivedEvent;
public
property Hostname: String read FHostname write FHostname;
public
constructor Create; override;
destructor Destroy; override;
public
procedure Connect; virtual;
procedure Disconnect; virtual;
procedure Send(const AMessage: String); virtual;
public
function IsConnected: Boolean; virtual;
public
property OnConnected: TConnectionEvent read FOnConnected write FOnConnected;
property OnDisconnected: TConnectionEvent read FOnDisconnected write FOnDisconnected;
property OnMessageReceived: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived;
{$ifdef FPC} property OnMessageRecieved: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; deprecated 'use OnMessageReceived'; {$endif}
end;
implementation
uses
CastleApplicationProperties;
//
//TThreadSynchronisationHandler
//
{$ifndef ANDROID}
class procedure TThreadSynchronisationHandler.Update(Sender: TObject);
begin
CheckSynchronize; //This has to be done in the main thread regularly to enable Synchronisation between threads.
end;
class procedure TThreadSynchronisationHandler.Initialise;
begin
if not IsInitialised then
begin
ApplicationProperties.OnUpdate.Add({$ifdef FPC}@{$endif}Update);
IsInitialised := true;
end;
end;
{$endif}
//
//TAndroidTCPConnectionService
//
{$ifdef ANDROID}
constructor TAndroidTCPConnectionService.Create;
begin
FConnectedDictionary := TConnectedDictionary.Create;
FKey := IntToHex(PtrUInt(Self), 1); //Key used for the identification is the unique pointer value of the class instance as hex string.
Messaging.OnReceive.Add(@MessageFilter);
end;
destructor TAndroidTCPConnectionService.Destroy;
begin
Close;
Messaging.OnReceive.Remove(@MessageFilter);
FConnectedDictionary.Free;
inherited;
end;
function TAndroidTCPConnectionService.MessageFilter(const Received: TCastleStringList;
const ReceivedStream: TMemoryStream): Boolean;
var
LConnectionStatus: Boolean;
begin
Result := false;
if (Received.Count = 4) and (Received[0] = AndroidServiceName) and (Received[1] = 'message') then //"client-server" "message" message clientid
begin
if Assigned(FMessageReceived) then
FMessageReceived(Received[2], TClientConnection.Create(Received[3]));
Result := true;
end
else if (Received.Count = 3) and (Received[0] = AndroidServiceName) and (Received[1] = 'connected') then //"client-server" "connected" clientid
begin
FConnectedDictionary.AddOrSetValue(Received[2], true);
if Assigned(FOnConnected) then
FOnConnected(TClientConnection.Create(Received[2]));
Result := true;
end
else if (Received.Count = 3) and (Received[0] = AndroidServiceName) and (Received[1] = 'disconnected') then //client-server "disconnected" clientid
begin
LConnectionStatus := false;
if Assigned(FOnDisconnected) and FConnectedDictionary.TryGetValue(Received[2], LConnectionStatus) and LConnectionStatus then
FOnDisconnected(TClientConnection.Create(Received[2])); //Only fire the event if the connection wasn't closed by us.
FConnectedDictionary.Remove(Received[2]);
if FConnectedDictionary.Count = 0 then
FIsActive := false;
Result := true;
end;
end;
procedure TAndroidTCPConnectionService.CreateServer(const APort: Word);
begin
if not FIsActive then
begin
Messaging.Send([AndroidServiceName, FKey, 'server', 'tcp', IntToStr(APort)]);
FIsActive := true;
end;
end;
procedure TAndroidTCPConnectionService.CreateClient(const AHost: String; const APort: Word);
begin
if not FIsActive then
begin
Messaging.Send([AndroidServiceName, FKey, 'client', 'tcp', AHost, IntToStr(APort)]);
FIsActive := true;
end;
end;
procedure TAndroidTCPConnectionService.SendMessage(const AMessage: String);
begin
SendMessage(AMessage, TClientConnection.Create('all'));
end;
procedure TAndroidTCPConnectionService.SendMessage(const AMessage: String; AClient: TClientConnection);
begin
if FIsActive then
Messaging.Send([AndroidServiceName, FKey, 'send', AMessage, AClient.ID]);
end;
procedure TAndroidTCPConnectionService.Close;
begin
Close(TClientConnection.Create('all'));
end;
procedure TAndroidTCPConnectionService.Close(AClient: TClientConnection);
begin
if FIsActive then
begin
FConnectedDictionary.AddOrSetValue(AClient.ID, false);
Messaging.Send([AndroidServiceName, FKey, 'close', AClient.ID]);
end;
end;
function TAndroidTCPConnectionService.IsConnected: Boolean;
var
B: Boolean;
begin
Result := false;
if FIsActive then
// is there any pair in FConnectedDictionary with value = true (connected)?
for B in FConnectedDictionary.Values do
if B then
Exit(true);
end;
function TAndroidTCPConnectionService.IsConnected(AClient: TClientConnection): Boolean;
begin
Result := false;
if FIsActive then
FConnectedDictionary.TryGetValue(AClient.ID, Result);
end;
{$endif}
//
//TCastleTCPClientThread
//
{$ifndef ANDROID}
constructor TCastleTCPClientThread.Create(const AClient: TIdTCPClient; const AOnMessageReceived, AOnConnected, AOnDisconnected: TProcedureObject);
begin
FClient := AClient;
FOnMessageReceived := AOnMessageReceived;
FOnConnected := AOnConnected;
FOnDisconnected := AOnDisconnected;
FMessageList := TSynchronisedStringList.Create;
inherited Create(false);
end;
destructor TCastleTCPClientThread.Destroy;
begin
FMessageList.Free;
inherited;
end;
procedure TCastleTCPClientThread.Execute;
var
LMessage: String;
begin
FClient.Connect;
FClient.IOHandler.ReadTimeout := 100;
{$ifdef FPC}
{ Change to use IndyTextEncoding_UTF8,
see TCastleTCPServer.ServerOnConnect for explanation. }
FClient.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
FClient.IOHandler.DefAnsiEncoding := IndyTextEncoding_UTF8;
{$endif}
if Assigned(FOnConnected) then
Queue(FOnConnected);
while not Terminated do
begin
try
LMessage := FClient.IOHandler.ReadLn; //Result is empty when timeout reached.
if LMessage <> '' then
begin
FMessageList.Add(LMessage);
Queue(FOnMessageReceived);
end;
except
//Exception occurs when connection was disconnected (gracefully).
Terminate;
if Assigned(FOnDisconnected) then
Synchronize(FOnDisconnected); //Must be synchronize, not queue, because queued messages get lost.
end;
end;
FClient.Disconnect;
if FreeClientOnTerminate then
FClient.Free;
end;
{$endif}
//
//TClientConnection
//
constructor TClientConnection.Create({$ifdef ANDROID}AID: String{$else}AContext: TIdContext{$endif});
begin
{$ifdef ANDROID}
ID := AID;
{$else}
Context := AContext;
{$endif}
end;
//
//TCastleSocket
//
constructor TCastleSocket.Create;
begin
{$ifdef ANDROID}
FTCPConnectionService := TAndroidTCPConnectionService.Create;
{$else}
TThreadSynchronisationHandler.Initialise;
{$endif}
end;
destructor TCastleSocket.Destroy;
begin
{$ifdef ANDROID}
FTCPConnectionService.Free;
{$endif}
inherited;
end;
//
//TCastleTCPServer
//
constructor TCastleTCPServer.Create;
begin
inherited;
{$ifndef ANDROID}
FClientConnectedList := TClientContextList.Create;
FClientDisconnectedList := TClientContextList.Create;
FClientConnectionsList := TClientContextList.Create;
FMessageList := TMessageClientList.Create;
FServer := TIdTCPServer.Create;
FServer.OnConnect := {$ifdef FPC}@{$endif} ServerOnConnect;
FServer.OnDisconnect := {$ifdef FPC}@{$endif} ServerOnDisconnect;
FServer.OnExecute := {$ifdef FPC}@{$endif} ServerOnExecute;
{$endif}
end;
destructor TCastleTCPServer.Destroy;
begin
{$ifndef ANDROID}
FServer.Free;
FClientConnectedList.Free;
FClientDisconnectedList.Free;
FClientConnectionsList.Free;
FMessageList.Free;
{$endif}
inherited;
end;
procedure TCastleTCPServer.Start;
{$ifdef UNIX}{$ifndef ANDROID}
var
Binding: TIdSocketHandle;
{$endif}{$endif}
begin
{$ifdef ANDROID}
FTCPConnectionService.OnMessageReceived := FOnMessageReceived;
FTCPConnectionService.OnConnected := FOnConnected;
FTCPConnectionService.OnDisconnected := FOnDisconnected;
FTCPConnectionService.CreateServer(FPort);
{$else}
{$ifdef UNIX}
Binding := FServer.Bindings.Add;
Binding.IP := '0.0.0.0';
Binding.Port := FPort;
{$else}
FServer.DefaultPort := FPort;
{$endif}
FServer.Active := true;
{$endif}
end;
procedure TCastleTCPServer.Stop;
begin
{$ifdef ANDROID}
FTCPConnectionService.Close;
{$else}
FServer.Active := false;
{$endif}
end;
procedure TCastleTCPServer.Disconnect(AClient: TClientConnection);
begin
{$ifdef ANDROID}
FTCPConnectionService.Close(AClient);
{$else}
AClient.Context.Data := AClient.Context; //Prevents the OnDisconnect event to fire after disconnect on our site.
AClient.Context.Connection.Disconnect;
{$endif}
end;
procedure TCastleTCPServer.SendToClient(const AMessage: String; AClient: TClientConnection);
begin
{$ifdef ANDROID}
FTCPConnectionService.SendMessage(AMessage, AClient);
{$else}
AClient.Context.Connection.IOHandler.WriteLn(AMessage);
{$endif}
end;
procedure TCastleTCPServer.SendToAll(const AMessage: String);
{$ifndef ANDROID}
var
LContext: TIdContext;
{$endif}
begin
{$ifdef ANDROID}
FTCPConnectionService.SendMessage(AMessage);
{$else}
for LContext in FClientConnectionsList.LockList do
LContext.Connection.IOHandler.WriteLn(AMessage);
FClientConnectionsList.UnlockList;
{$endif}
end;
function TCastleTCPServer.IsConnected: Boolean;
begin
{$ifdef ANDROID}
Result := FTCPConnectionService.IsConnected;
{$else}
Result := FClientConnectionsList.LockList.Count > 0;
FClientConnectionsList.UnlockList;
{$endif}
end;
function TCastleTCPServer.IsConnected(AClient: TClientConnection): Boolean;
begin
{$ifdef ANDROID}
Result := FTCPConnectionService.IsConnected(AClient);
{$else}
Result := FClientConnectionsList.LockList.IndexOf(AClient.Context) > -1;
FClientConnectionsList.UnlockList;
{$endif}
end;
{$ifndef ANDROID}
procedure TCastleTCPServer.ServerOnConnect(AContext: TIdContext);
begin
FClientConnectedList.Add(AContext);
FClientConnectionsList.Add(AContext);
AContext.Connection.IOHandler.ReadTimeout := 100;
{$ifdef FPC}
{ Change to use IndyTextEncoding_UTF8, to enable sending/receiving
UTF-8 encoded strings in FPC (as just String = AnsiString).
FPC Indy from http://packages.lazarus-ide.org/Indy10.zip has by default
DefStringEncoding = IndyTextEncoding_ASCII
DefAnsiEncoding = IndyTextEncoding_OSDefault
We need to change both DefAnsiEncoding (seems to matter to send them OK)
and DefStringEncoding (seems to matter to receive the non-ASCII chars OK).
Without any change, sending non-ASCII characters encoded in UTF-8
is silently ignored (whole message was ignored).
Reproduced on at least Linux and FreeBSD with FPC 3.2.2
(see https://github.com/castle-engine/castle-engine/issues/590). }
AContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
AContext.Connection.IOHandler.DefAnsiEncoding := IndyTextEncoding_UTF8;
{$endif}
if Assigned(FOnConnected) then
TThread.Queue(nil, {$ifdef FPC}@{$endif} ServerOnClientConnected);
end;
procedure TCastleTCPServer.ServerOnDisconnect(AContext: TIdContext);
begin
FClientConnectionsList.Remove(AContext);
FClientDisconnectedList.Add(AContext);
if Assigned(FOnDisconnected) and (AContext.Data = nil) and FServer.Active then
TThread.Synchronize(nil, {$ifdef FPC}@{$endif} ServerOnClientDisconnected); //Disconnect must be synchronized, not queued, because else the queued message gets losed.
end;
procedure TCastleTCPServer.ServerOnExecute(AContext: TIdContext);
var
LMessageClientRecord: TMessageClientRecord;
begin
LMessageClientRecord.Message := AContext.Connection.IOHandler.ReadLn;
if LMessageClientRecord.Message <> '' then
begin
LMessageClientRecord.Client := TClientConnection.Create(AContext);
FMessageList.Add(LMessageClientRecord);
TThread.Queue(nil, {$ifdef FPC}@{$endif} ServerOnMessageReceived);
end;
end;
procedure TCastleTCPServer.ServerOnClientConnected;
var
LContext: TIdContext;
begin
if Assigned(FOnConnected) then
begin
for LContext in FClientConnectedList.LockList do
FOnConnected(TClientConnection.Create(LContext));
FClientConnectedList.Clear;
FClientConnectedList.UnlockList;
end;
end;
procedure TCastleTCPServer.ServerOnClientDisconnected;
var
LContext: TIdContext;
begin
if Assigned(FOnDisconnected) then
begin
for LContext in FClientDisconnectedList.LockList do
FOnDisconnected(TClientConnection.Create(LContext));
FClientDisconnectedList.Clear;
FClientDisconnectedList.UnlockList;
end;
end;
procedure TCastleTCPServer.ServerOnMessageReceived;
var
LMessageClientRecord: TMessageClientRecord;
begin
if Assigned(FOnMessageReceived) then
begin
for LMessageClientRecord in FMessageList.LockList do
FOnMessageReceived(LMessageClientRecord.Message, LMessageClientRecord.Client);
FMessageList.Clear;
FMessageList.UnlockList;
end;
end;
{$endif}
//
//TCastleTCPClient
//
constructor TCastleTCPClient.Create;
begin
inherited;
{$ifndef ANDROID}
FClient := TIdTCPClient.Create;
FClient.ConnectTimeout := 5000;
{$endif}
end;
destructor TCastleTCPClient.Destroy;
begin
{$ifndef ANDROID}
if FClientThread <> nil then
begin
FClientThread.FreeClientOnTerminate := true;
FClient := nil; // will be freed because of FClientThread.FreeClientOnTerminate
FClientThread.FreeOnTerminate := true;
FClientThread.Terminate;
FClientThread := nil; // will free itself because FreeOnTerminate = true, so don't keep reference to it
end else
begin
{ If no FClientThread, free FClient ourselves. }
FreeAndNil(FClient);
end;
{$endif}
inherited;
end;
procedure TCastleTCPClient.Connect;
begin
{$ifdef ANDROID}
FTCPConnectionService.OnConnected := @ClientOnClientConnected;
FTCPConnectionService.OnDisconnected := @ClientOnClientDisconnected;
FTCPConnectionService.OnMessageReceived := @ClientOnMessageReceived;
FTCPConnectionService.CreateClient(FHostname, FPort);
{$else}
FClient.Port := FPort;
FClient.Host := FHostname;
FClientThread := TCastleTCPClientThread.Create(FClient,
{$ifdef FPC}@{$endif} ClientOnMessageReceived, FOnConnected, FOnDisconnected);
{$endif}
end;
procedure TCastleTCPClient.Disconnect;
begin
{$ifdef ANDROID}
FTCPConnectionService.Close;
{$else}
FClientThread.FreeOnTerminate := true;
FClientThread.Terminate;
FClientThread := nil; // will free itself because FreeOnTerminate = true, so don't keep reference to it
{$endif}
end;
procedure TCastleTCPClient.Send(const AMessage: String);
begin
if not IsConnected then
raise Exception.Create('Cannot send message because not connected');
{$ifdef ANDROID}
FTCPConnectionService.SendMessage(AMessage);
{$else}
Assert(FClient.IOHandler <> nil); // checking IsConnected should guarantee this
FClient.IOHandler.WriteLn(AMessage);
{$endif}
end;
function TCastleTCPClient.IsConnected: Boolean;
begin
{$ifdef ANDROID}
Result := FTCPConnectionService.IsConnected;
{$else}
Result := FClient.Connected;
if Result then
Assert(FClient.IOHandler <> nil);
{$endif}
end;
{$ifdef ANDROID}
procedure TCastleTCPClient.ClientOnClientConnected(AClientConnection: TClientConnection);
begin
if Assigned(FOnConnected) then
FOnConnected();
end;
procedure TCastleTCPClient.ClientOnClientDisconnected(AClientConnection: TClientConnection);
begin
if Assigned(FOnDisconnected) then
FOnDisconnected();
end;
procedure TCastleTCPClient.ClientOnMessageReceived(const AMessage: String; AClientConnection: TClientConnection);
begin
if Assigned(FOnMessageReceived) then
FOnMessageReceived(AMessage);
end;
{$else}
procedure TCastleTCPClient.ClientOnMessageReceived;
var
LMessage: String;
begin
if Assigned(FOnMessageReceived) then
begin
for LMessage in FClientThread.MessageList.LockList do
FOnMessageReceived(LMessage);
FClientThread.MessageList.Clear;
FClientThread.MessageList.UnlockList;
end;
end;
{$endif}
end.