Debian Codegraph @

src/files/indy/castleclientserver.pas

raw
1 {
2 Copyright 2018-2024 Benedikt Magnus, Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Client and server for network communication using TCP (TCastleTCPClient, TCastleTCPServer).
17 Use this in your games for easy client/server communication.
18 See https://castle-engine.io/manual_network.php#section_multi_player .
19
20 On Android, it requires adding
21 @url(https://castle-engine.io/android-Services
22 client_server service in your project).
23 On other platforms, it requires having @url(http://www.indyproject.org/ Indy) available. }
24 unit CastleClientServer;
25
26 {$I castleconf.inc}
27
28 interface
29
30 uses
31 Classes, SysUtils, Generics.Collections,
32 {$ifdef ANDROID}
33 CastleMessaging, CastleStringUtils
34 {$else}
35 IdTCPServer, IdTCPClient, IdContext, IdSocketHandle, IdGlobal
36 {$endif};
37
38 type
39 TClientConnection = record
40 private
41 {$ifndef ANDROID}
42 Context: TIdContext;
43 {$else}
44 ID: String;
45 {$endif}
46 public
47 constructor Create({$ifdef ANDROID}AID: String{$else}AContext: TIdContext{$endif});
48 end;
49
50 TProcedureObject = procedure of object;
51
52 TConnectionEvent = procedure of object;
53 TClientConnectionEvent = procedure(AClientConnection: TClientConnection) of object;
54
55 TMessageReceivedEvent = procedure(const AMessage: String) of object;
56 TClientMessageReceivedEvent = procedure(const AMessage: String; AClientConnection: TClientConnection) of object;
57
58 TSynchronisedStringList = {$ifdef FPC}specialize{$endif} TThreadList<String>;
59
60 {$ifndef ANDROID}
61 type
62 TMessageClientRecord = record
63 Message: String;
64 Client: TClientConnection;
65 end;
66
67 TMessageClientList = {$ifdef FPC}specialize{$endif} TThreadList<TMessageClientRecord>;
68 TClientContextList = {$ifdef FPC}specialize{$endif} TThreadList<TIdContext>; //Because Indys version isn't generic in FPC.
69 {$endif}
70
71 {$ifndef ANDROID}
72 type
73 TThreadSynchronisationHandler = class
74 protected
75 class var IsInitialised: Boolean;
76 class procedure Update(Sender: TObject);
77 public
78 class procedure Initialise;
79 end;
80 {$endif}
81
82 {$ifdef ANDROID}
83 type
84 TConnectedDictionary = specialize TDictionary<String, Boolean>;
85
86 TAndroidTCPConnectionService = class
87 strict protected
88 const AndroidServiceName = 'client-server';
89 strict protected
90 FMessageReceived: TClientMessageReceivedEvent;
91 FOnConnected: TClientConnectionEvent;
92 FOnDisconnected: TClientConnectionEvent;
93 FConnectedDictionary: TConnectedDictionary;
94 FKey: String;
95 FIsActive: Boolean;
96 function MessageFilter(const Received: TCastleStringList;
97 const ReceivedStream: TMemoryStream): Boolean;
98 public
99 constructor Create;
100 destructor Destroy; override;
101 public
102 procedure CreateServer(const APort: Word);
103 procedure CreateClient(const AHost: String; const APort: Word);
104 procedure SendMessage(const AMessage: String); overload;
105 procedure SendMessage(const AMessage: String; AClient: TClientConnection); overload;
106 procedure Close; overload;
107 procedure Close(AClient: TClientConnection); overload;
108 public
109 property OnConnected: TClientConnectionEvent write FOnConnected;
110 property OnDisconnected: TClientConnectionEvent write FOnDisconnected;
111 property OnMessageReceived: TClientMessageReceivedEvent write FMessageReceived;
112 {$ifdef FPC} property OnMessageRecieved: TClientMessageReceivedEvent write FMessageReceived; deprecated 'use OnMessageReceived'; {$endif}
113 public
114 function IsConnected: Boolean; overload;
115 function IsConnected(AClient: TClientConnection): Boolean; overload;
116 end;
117 {$else}
118 type
119 TCastleTCPClientThread = class(TThread)
120 strict protected
121 FClient: TIdTCPClient;
122 FOnConnected: TProcedureObject;
123 FOnDisconnected: TProcedureObject;
124 FOnMessageReceived: TProcedureObject;
125 strict protected
126 FMessageList: TSynchronisedStringList;
127 protected
128 procedure Execute; override;
129 public
130 constructor Create(const AClient: TIdTCPClient; const AOnMessageReceived, AOnConnected, AOnDisconnected: TProcedureObject); virtual;
131 destructor Destroy; override;
132 public
133 FreeClientOnTerminate: Boolean;
134 property MessageList: TSynchronisedStringList read FMessageList;
135 end;
136 {$endif}
137
138 type
139 TCastleSocket = class
140 strict protected
141 {$ifdef ANDROID}
142 FTCPConnectionService: TAndroidTCPConnectionService;
143 {$endif}
144 FPort: Word;
145 public
146 property Port: Word read FPort write FPort;
147 public
148 constructor Create; virtual;
149 destructor Destroy; override;
150 end;
151
152 TCastleTCPServer = class(TCastleSocket)
153 strict protected
154 {$ifndef ANDROID}
155 FServer: TIdTCPServer;
156 FClientConnectedList: TClientContextList; //Temporary list for all NEW connected clients.
157 FClientDisconnectedList: TClientContextList; //Same for all disconnected clients.
158 FClientConnectionsList: TClientContextList; //List for all CURRENTLY connected clients.
159 FMessageList: TMessageClientList;
160 procedure ServerOnConnect(AContext: TIdContext);
161 procedure ServerOnDisconnect(AContext: TIdContext);
162 procedure ServerOnExecute(AContext: TIdContext);
163 procedure ServerOnClientConnected;
164 procedure ServerOnClientDisconnected;
165 procedure ServerOnMessageReceived;
166 {$endif}
167 strict protected
168 FOnConnected: TClientConnectionEvent;
169 FOnDisconnected: TClientConnectionEvent;
170 FOnMessageReceived: TClientMessageReceivedEvent;
171 public
172 constructor Create; override;
173 destructor Destroy; override;
174 public
175 procedure Start; virtual;
176 procedure Stop; virtual;
177 procedure Disconnect(AClient: TClientConnection); virtual;
178 procedure SendToClient(const AMessage: String; AClient: TClientConnection); virtual;
179 procedure SendToAll(const AMessage: String); virtual;
180 public
181 function IsConnected: Boolean; overload; virtual;
182 function IsConnected(AClient: TClientConnection): Boolean; overload; virtual;
183 public
184 property OnConnected: TClientConnectionEvent read FOnConnected write FOnConnected;
185 property OnDisconnected: TClientConnectionEvent read FOnDisconnected write FOnDisconnected;
186 property OnMessageReceived: TClientMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived;
187 {$ifdef FPC} property OnMessageRecieved: TClientMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; deprecated 'use OnMessageReceived'; {$endif}
188 end;
189
190 TCastleTCPClient = class(TCastleSocket)
191 strict protected
192 FHostname: String;
193 {$ifdef ANDROID}
194 procedure ClientOnClientConnected(AClientConnection: TClientConnection);
195 procedure ClientOnClientDisconnected(AClientConnection: TClientConnection);
196 procedure ClientOnMessageReceived(const AMessage: String; AClientConnection: TClientConnection);
197 {$else}
198 FClient: TIdTCPClient;
199 FClientThread: TCastleTCPClientThread;
200 procedure ClientOnMessageReceived;
201 {$endif}
202 strict protected
203 FOnConnected: TConnectionEvent;
204 FOnDisconnected: TConnectionEvent;
205 FOnMessageReceived: TMessageReceivedEvent;
206 public
207 property Hostname: String read FHostname write FHostname;
208 public
209 constructor Create; override;
210 destructor Destroy; override;
211 public
212 procedure Connect; virtual;
213 procedure Disconnect; virtual;
214 procedure Send(const AMessage: String); virtual;
215 public
216 function IsConnected: Boolean; virtual;
217 public
218 property OnConnected: TConnectionEvent read FOnConnected write FOnConnected;
219 property OnDisconnected: TConnectionEvent read FOnDisconnected write FOnDisconnected;
220 property OnMessageReceived: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived;
221 {$ifdef FPC} property OnMessageRecieved: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; deprecated 'use OnMessageReceived'; {$endif}
222 end;
223
224 implementation
225
226 uses
227 CastleApplicationProperties;
228
229 //
230 //TThreadSynchronisationHandler
231 //
232
233 {$ifndef ANDROID}
234 class procedure TThreadSynchronisationHandler.Update(Sender: TObject);
235 begin
236 CheckSynchronize; //This has to be done in the main thread regularly to enable Synchronisation between threads.
237 end;
238
239 class procedure TThreadSynchronisationHandler.Initialise;
240 begin
241 if not IsInitialised then
242 begin
243 ApplicationProperties.OnUpdate.Add({$ifdef FPC}@{$endif}Update);
244 IsInitialised := true;
245 end;
246 end;
247 {$endif}
248
249 //
250 //TAndroidTCPConnectionService
251 //
252
253 {$ifdef ANDROID}
254 constructor TAndroidTCPConnectionService.Create;
255 begin
256 FConnectedDictionary := TConnectedDictionary.Create;
257
258 FKey := IntToHex(PtrUInt(Self), 1); //Key used for the identification is the unique pointer value of the class instance as hex string.
259 Messaging.OnReceive.Add(@MessageFilter);
260 end;
261
262 destructor TAndroidTCPConnectionService.Destroy;
263 begin
264 Close;
265
266 Messaging.OnReceive.Remove(@MessageFilter);
267
268 FConnectedDictionary.Free;
269
270 inherited;
271 end;
272
273 function TAndroidTCPConnectionService.MessageFilter(const Received: TCastleStringList;
274 const ReceivedStream: TMemoryStream): Boolean;
275 var
276 LConnectionStatus: Boolean;
277 begin
278 Result := false;
279 if (Received.Count = 4) and (Received[0] = AndroidServiceName) and (Received[1] = 'message') then //"client-server" "message" message clientid
280 begin
281 if Assigned(FMessageReceived) then
282 FMessageReceived(Received[2], TClientConnection.Create(Received[3]));
283 Result := true;
284 end
285 else if (Received.Count = 3) and (Received[0] = AndroidServiceName) and (Received[1] = 'connected') then //"client-server" "connected" clientid
286 begin
287 FConnectedDictionary.AddOrSetValue(Received[2], true);
288 if Assigned(FOnConnected) then
289 FOnConnected(TClientConnection.Create(Received[2]));
290 Result := true;
291 end
292 else if (Received.Count = 3) and (Received[0] = AndroidServiceName) and (Received[1] = 'disconnected') then //client-server "disconnected" clientid
293 begin
294 LConnectionStatus := false;
295 if Assigned(FOnDisconnected) and FConnectedDictionary.TryGetValue(Received[2], LConnectionStatus) and LConnectionStatus then
296 FOnDisconnected(TClientConnection.Create(Received[2])); //Only fire the event if the connection wasn't closed by us.
297
298 FConnectedDictionary.Remove(Received[2]);
299
300 if FConnectedDictionary.Count = 0 then
301 FIsActive := false;
302
303 Result := true;
304 end;
305 end;
306
307 procedure TAndroidTCPConnectionService.CreateServer(const APort: Word);
308 begin
309 if not FIsActive then
310 begin
311 Messaging.Send([AndroidServiceName, FKey, 'server', 'tcp', IntToStr(APort)]);
312 FIsActive := true;
313 end;
314 end;
315
316 procedure TAndroidTCPConnectionService.CreateClient(const AHost: String; const APort: Word);
317 begin
318 if not FIsActive then
319 begin
320 Messaging.Send([AndroidServiceName, FKey, 'client', 'tcp', AHost, IntToStr(APort)]);
321 FIsActive := true;
322 end;
323 end;
324
325 procedure TAndroidTCPConnectionService.SendMessage(const AMessage: String);
326 begin
327 SendMessage(AMessage, TClientConnection.Create('all'));
328 end;
329
330 procedure TAndroidTCPConnectionService.SendMessage(const AMessage: String; AClient: TClientConnection);
331 begin
332 if FIsActive then
333 Messaging.Send([AndroidServiceName, FKey, 'send', AMessage, AClient.ID]);
334 end;
335
336 procedure TAndroidTCPConnectionService.Close;
337 begin
338 Close(TClientConnection.Create('all'));
339 end;
340
341 procedure TAndroidTCPConnectionService.Close(AClient: TClientConnection);
342 begin
343 if FIsActive then
344 begin
345 FConnectedDictionary.AddOrSetValue(AClient.ID, false);
346 Messaging.Send([AndroidServiceName, FKey, 'close', AClient.ID]);
347 end;
348 end;
349
350 function TAndroidTCPConnectionService.IsConnected: Boolean;
351 var
352 B: Boolean;
353 begin
354 Result := false;
355 if FIsActive then
356 // is there any pair in FConnectedDictionary with value = true (connected)?
357 for B in FConnectedDictionary.Values do
358 if B then
359 Exit(true);
360 end;
361
362 function TAndroidTCPConnectionService.IsConnected(AClient: TClientConnection): Boolean;
363 begin
364 Result := false;
365 if FIsActive then
366 FConnectedDictionary.TryGetValue(AClient.ID, Result);
367 end;
368 {$endif}
369
370 //
371 //TCastleTCPClientThread
372 //
373
374 {$ifndef ANDROID}
375 constructor TCastleTCPClientThread.Create(const AClient: TIdTCPClient; const AOnMessageReceived, AOnConnected, AOnDisconnected: TProcedureObject);
376 begin
377 FClient := AClient;
378 FOnMessageReceived := AOnMessageReceived;
379 FOnConnected := AOnConnected;
380 FOnDisconnected := AOnDisconnected;
381
382 FMessageList := TSynchronisedStringList.Create;
383
384 inherited Create(false);
385 end;
386
387 destructor TCastleTCPClientThread.Destroy;
388 begin
389 FMessageList.Free;
390
391 inherited;
392 end;
393
394 procedure TCastleTCPClientThread.Execute;
395 var
396 LMessage: String;
397 begin
398 FClient.Connect;
399 FClient.IOHandler.ReadTimeout := 100;
400 {$ifdef FPC}
401 { Change to use IndyTextEncoding_UTF8,
402 see TCastleTCPServer.ServerOnConnect for explanation. }
403 FClient.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
404 FClient.IOHandler.DefAnsiEncoding := IndyTextEncoding_UTF8;
405 {$endif}
406
407 if Assigned(FOnConnected) then
408 Queue(FOnConnected);
409
410 while not Terminated do
411 begin
412 try
413 LMessage := FClient.IOHandler.ReadLn; //Result is empty when timeout reached.
414
415 if LMessage <> '' then
416 begin
417 FMessageList.Add(LMessage);
418 Queue(FOnMessageReceived);
419 end;
420 except
421 //Exception occurs when connection was disconnected (gracefully).
422 Terminate;
423 if Assigned(FOnDisconnected) then
424 Synchronize(FOnDisconnected); //Must be synchronize, not queue, because queued messages get lost.
425 end;
426 end;
427 FClient.Disconnect;
428 if FreeClientOnTerminate then
429 FClient.Free;
430 end;
431 {$endif}
432
433 //
434 //TClientConnection
435 //
436
437 constructor TClientConnection.Create({$ifdef ANDROID}AID: String{$else}AContext: TIdContext{$endif});
438 begin
439 {$ifdef ANDROID}
440 ID := AID;
441 {$else}
442 Context := AContext;
443 {$endif}
444 end;
445
446 //
447 //TCastleSocket
448 //
449
450 constructor TCastleSocket.Create;
451 begin
452 {$ifdef ANDROID}
453 FTCPConnectionService := TAndroidTCPConnectionService.Create;
454 {$else}
455 TThreadSynchronisationHandler.Initialise;
456 {$endif}
457 end;
458
459 destructor TCastleSocket.Destroy;
460 begin
461 {$ifdef ANDROID}
462 FTCPConnectionService.Free;
463 {$endif}
464
465 inherited;
466 end;
467
468 //
469 //TCastleTCPServer
470 //
471
472 constructor TCastleTCPServer.Create;
473 begin
474 inherited;
475
476 {$ifndef ANDROID}
477 FClientConnectedList := TClientContextList.Create;
478 FClientDisconnectedList := TClientContextList.Create;
479 FClientConnectionsList := TClientContextList.Create;
480 FMessageList := TMessageClientList.Create;
481
482 FServer := TIdTCPServer.Create;
483 FServer.OnConnect := {$ifdef FPC}@{$endif} ServerOnConnect;
484 FServer.OnDisconnect := {$ifdef FPC}@{$endif} ServerOnDisconnect;
485 FServer.OnExecute := {$ifdef FPC}@{$endif} ServerOnExecute;
486 {$endif}
487 end;
488
489 destructor TCastleTCPServer.Destroy;
490 begin
491 {$ifndef ANDROID}
492 FServer.Free;
493 FClientConnectedList.Free;
494 FClientDisconnectedList.Free;
495 FClientConnectionsList.Free;
496 FMessageList.Free;
497 {$endif}
498
499 inherited;
500 end;
501
502 procedure TCastleTCPServer.Start;
503 {$ifdef UNIX}{$ifndef ANDROID}
504 var
505 Binding: TIdSocketHandle;
506 {$endif}{$endif}
507 begin
508 {$ifdef ANDROID}
509 FTCPConnectionService.OnMessageReceived := FOnMessageReceived;
510 FTCPConnectionService.OnConnected := FOnConnected;
511 FTCPConnectionService.OnDisconnected := FOnDisconnected;
512 FTCPConnectionService.CreateServer(FPort);
513 {$else}
514 {$ifdef UNIX}
515 Binding := FServer.Bindings.Add;
516 Binding.IP := '0.0.0.0';
517 Binding.Port := FPort;
518 {$else}
519 FServer.DefaultPort := FPort;
520 {$endif}
521 FServer.Active := true;
522 {$endif}
523 end;
524
525 procedure TCastleTCPServer.Stop;
526 begin
527 {$ifdef ANDROID}
528 FTCPConnectionService.Close;
529 {$else}
530 FServer.Active := false;
531 {$endif}
532 end;
533
534 procedure TCastleTCPServer.Disconnect(AClient: TClientConnection);
535 begin
536 {$ifdef ANDROID}
537 FTCPConnectionService.Close(AClient);
538 {$else}
539 AClient.Context.Data := AClient.Context; //Prevents the OnDisconnect event to fire after disconnect on our site.
540 AClient.Context.Connection.Disconnect;
541 {$endif}
542 end;
543
544 procedure TCastleTCPServer.SendToClient(const AMessage: String; AClient: TClientConnection);
545 begin
546 {$ifdef ANDROID}
547 FTCPConnectionService.SendMessage(AMessage, AClient);
548 {$else}
549 AClient.Context.Connection.IOHandler.WriteLn(AMessage);
550 {$endif}
551 end;
552
553 procedure TCastleTCPServer.SendToAll(const AMessage: String);
554 {$ifndef ANDROID}
555 var
556 LContext: TIdContext;
557 {$endif}
558 begin
559 {$ifdef ANDROID}
560 FTCPConnectionService.SendMessage(AMessage);
561 {$else}
562 for LContext in FClientConnectionsList.LockList do
563 LContext.Connection.IOHandler.WriteLn(AMessage);
564 FClientConnectionsList.UnlockList;
565 {$endif}
566 end;
567
568 function TCastleTCPServer.IsConnected: Boolean;
569 begin
570 {$ifdef ANDROID}
571 Result := FTCPConnectionService.IsConnected;
572 {$else}
573 Result := FClientConnectionsList.LockList.Count > 0;
574 FClientConnectionsList.UnlockList;
575 {$endif}
576 end;
577
578 function TCastleTCPServer.IsConnected(AClient: TClientConnection): Boolean;
579 begin
580 {$ifdef ANDROID}
581 Result := FTCPConnectionService.IsConnected(AClient);
582 {$else}
583 Result := FClientConnectionsList.LockList.IndexOf(AClient.Context) > -1;
584 FClientConnectionsList.UnlockList;
585 {$endif}
586 end;
587
588 {$ifndef ANDROID}
589 procedure TCastleTCPServer.ServerOnConnect(AContext: TIdContext);
590 begin
591 FClientConnectedList.Add(AContext);
592 FClientConnectionsList.Add(AContext);
593
594 AContext.Connection.IOHandler.ReadTimeout := 100;
595 {$ifdef FPC}
596 { Change to use IndyTextEncoding_UTF8, to enable sending/receiving
597 UTF-8 encoded strings in FPC (as just String = AnsiString).
598
599 FPC Indy from http://packages.lazarus-ide.org/Indy10.zip has by default
600
601 DefStringEncoding = IndyTextEncoding_ASCII
602 DefAnsiEncoding = IndyTextEncoding_OSDefault
603
604 We need to change both DefAnsiEncoding (seems to matter to send them OK)
605 and DefStringEncoding (seems to matter to receive the non-ASCII chars OK).
606 Without any change, sending non-ASCII characters encoded in UTF-8
607 is silently ignored (whole message was ignored).
608 Reproduced on at least Linux and FreeBSD with FPC 3.2.2
609 (see https://github.com/castle-engine/castle-engine/issues/590). }
610 AContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
611 AContext.Connection.IOHandler.DefAnsiEncoding := IndyTextEncoding_UTF8;
612 {$endif}
613
614 if Assigned(FOnConnected) then
615 TThread.Queue(nil, {$ifdef FPC}@{$endif} ServerOnClientConnected);
616 end;
617
618 procedure TCastleTCPServer.ServerOnDisconnect(AContext: TIdContext);
619 begin
620 FClientConnectionsList.Remove(AContext);
621 FClientDisconnectedList.Add(AContext);
622
623 if Assigned(FOnDisconnected) and (AContext.Data = nil) and FServer.Active then
624 TThread.Synchronize(nil, {$ifdef FPC}@{$endif} ServerOnClientDisconnected); //Disconnect must be synchronized, not queued, because else the queued message gets losed.
625 end;
626
627 procedure TCastleTCPServer.ServerOnExecute(AContext: TIdContext);
628 var
629 LMessageClientRecord: TMessageClientRecord;
630 begin
631 LMessageClientRecord.Message := AContext.Connection.IOHandler.ReadLn;
632
633 if LMessageClientRecord.Message <> '' then
634 begin
635 LMessageClientRecord.Client := TClientConnection.Create(AContext);
636
637 FMessageList.Add(LMessageClientRecord);
638
639 TThread.Queue(nil, {$ifdef FPC}@{$endif} ServerOnMessageReceived);
640 end;
641 end;
642
643 procedure TCastleTCPServer.ServerOnClientConnected;
644 var
645 LContext: TIdContext;
646 begin
647 if Assigned(FOnConnected) then
648 begin
649 for LContext in FClientConnectedList.LockList do
650 FOnConnected(TClientConnection.Create(LContext));
651 FClientConnectedList.Clear;
652 FClientConnectedList.UnlockList;
653 end;
654 end;
655
656 procedure TCastleTCPServer.ServerOnClientDisconnected;
657 var
658 LContext: TIdContext;
659 begin
660 if Assigned(FOnDisconnected) then
661 begin
662 for LContext in FClientDisconnectedList.LockList do
663 FOnDisconnected(TClientConnection.Create(LContext));
664 FClientDisconnectedList.Clear;
665 FClientDisconnectedList.UnlockList;
666 end;
667 end;
668
669 procedure TCastleTCPServer.ServerOnMessageReceived;
670 var
671 LMessageClientRecord: TMessageClientRecord;
672 begin
673 if Assigned(FOnMessageReceived) then
674 begin
675 for LMessageClientRecord in FMessageList.LockList do
676 FOnMessageReceived(LMessageClientRecord.Message, LMessageClientRecord.Client);
677 FMessageList.Clear;
678 FMessageList.UnlockList;
679 end;
680 end;
681 {$endif}
682
683 //
684 //TCastleTCPClient
685 //
686
687 constructor TCastleTCPClient.Create;
688 begin
689 inherited;
690
691 {$ifndef ANDROID}
692 FClient := TIdTCPClient.Create;
693 FClient.ConnectTimeout := 5000;
694 {$endif}
695 end;
696
697 destructor TCastleTCPClient.Destroy;
698 begin
699 {$ifndef ANDROID}
700 if FClientThread <> nil then
701 begin
702 FClientThread.FreeClientOnTerminate := true;
703 FClient := nil; // will be freed because of FClientThread.FreeClientOnTerminate
704
705 FClientThread.FreeOnTerminate := true;
706 FClientThread.Terminate;
707 FClientThread := nil; // will free itself because FreeOnTerminate = true, so don't keep reference to it
708 end else
709 begin
710 { If no FClientThread, free FClient ourselves. }
711 FreeAndNil(FClient);
712 end;
713 {$endif}
714
715 inherited;
716 end;
717
718 procedure TCastleTCPClient.Connect;
719 begin
720 {$ifdef ANDROID}
721 FTCPConnectionService.OnConnected := @ClientOnClientConnected;
722 FTCPConnectionService.OnDisconnected := @ClientOnClientDisconnected;
723 FTCPConnectionService.OnMessageReceived := @ClientOnMessageReceived;
724 FTCPConnectionService.CreateClient(FHostname, FPort);
725 {$else}
726 FClient.Port := FPort;
727 FClient.Host := FHostname;
728
729 FClientThread := TCastleTCPClientThread.Create(FClient,
730 {$ifdef FPC}@{$endif} ClientOnMessageReceived, FOnConnected, FOnDisconnected);
731 {$endif}
732 end;
733
734 procedure TCastleTCPClient.Disconnect;
735 begin
736 {$ifdef ANDROID}
737 FTCPConnectionService.Close;
738 {$else}
739 FClientThread.FreeOnTerminate := true;
740 FClientThread.Terminate;
741 FClientThread := nil; // will free itself because FreeOnTerminate = true, so don't keep reference to it
742 {$endif}
743 end;
744
745 procedure TCastleTCPClient.Send(const AMessage: String);
746 begin
747 if not IsConnected then
748 raise Exception.Create('Cannot send message because not connected');
749
750 {$ifdef ANDROID}
751 FTCPConnectionService.SendMessage(AMessage);
752 {$else}
753 Assert(FClient.IOHandler <> nil); // checking IsConnected should guarantee this
754 FClient.IOHandler.WriteLn(AMessage);
755 {$endif}
756 end;
757
758 function TCastleTCPClient.IsConnected: Boolean;
759 begin
760 {$ifdef ANDROID}
761 Result := FTCPConnectionService.IsConnected;
762 {$else}
763 Result := FClient.Connected;
764 if Result then
765 Assert(FClient.IOHandler <> nil);
766 {$endif}
767 end;
768
769 {$ifdef ANDROID}
770 procedure TCastleTCPClient.ClientOnClientConnected(AClientConnection: TClientConnection);
771 begin
772 if Assigned(FOnConnected) then
773 FOnConnected();
774 end;
775
776 procedure TCastleTCPClient.ClientOnClientDisconnected(AClientConnection: TClientConnection);
777 begin
778 if Assigned(FOnDisconnected) then
779 FOnDisconnected();
780 end;
781
782 procedure TCastleTCPClient.ClientOnMessageReceived(const AMessage: String; AClientConnection: TClientConnection);
783 begin
784 if Assigned(FOnMessageReceived) then
785 FOnMessageReceived(AMessage);
786 end;
787 {$else}
788 procedure TCastleTCPClient.ClientOnMessageReceived;
789 var
790 LMessage: String;
791 begin
792 if Assigned(FOnMessageReceived) then
793 begin
794 for LMessage in FClientThread.MessageList.LockList do
795 FOnMessageReceived(LMessage);
796 FClientThread.MessageList.Clear;
797 FClientThread.MessageList.UnlockList;
798 end;
799 end;
800 {$endif}
801
802 end.