IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

 Delphi Discussion :

D6 Stream pour lire un fichier qui n'est pas fini d'écrire


Sujet :

Delphi

  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    322
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Janvier 2009
    Messages : 322
    Points : 310
    Points
    310
    Par défaut D6 Stream pour lire un fichier qui n'est pas fini d'écrire
    Bonjour à tous

    J'ai une application externe qui écrit un gros fichier.

    Toutefois j'aimerais le lire via une application Delphi dès le début de l'écriture de ce fichier.

    Est-ce possible avec un stream ?

    Si oui, comment sait-on qu'il est temps de suspendre la lecture, puis de reprendre la lecture?

    Il y aurait-il une autre façon de communiquer directement (et simplement) entre ces deux applications?

    Merci d'avance

  2. #2
    Membre émérite
    Avatar de ALWEBER
    Homme Profil pro
    Expert Delphi
    Inscrit en
    Mars 2006
    Messages
    1 496
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 69
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Expert Delphi

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 496
    Points : 2 762
    Points
    2 762
    Billets dans le blog
    10
    Par défaut
    Intuitivement je dirai non car l'application externe doit bloquer le fichier lors de l'écriture.

  3. #3
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 455
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 455
    Points : 24 867
    Points
    24 867
    Par défaut
    Cela dépend effectivement de la méthode d'écriture de l'application
    Cela m'arrive très souvent d'ouvrir un fichier log avec Notepad++, il détecte automatiquement que le fichier change de taille
    J'ai fait pour une ancienne version du client IRC XChat, un système utilisant les logs de discussion pour créer un balloonhint, fonctionnalité qui existe dans la version devenu payante de XChat.
    Je le mentionnais dans le sujet Lire un fichier seulement si celui-ci n'est pas déjà en cours de lecture/ecriture ?

    Voici la classe TNotifyShaiFileChangeThread et TFileSizeList
    Tu implémentes un gestionnaire d'événement du OnChange du type TFileMessageEvent
    Cela lit de le Delta entre deux lectures, une sorte de lecture incrémentielle, je te laisse étudier ces 3 liens et modifier cela selon tes besoins



    Si c'est pour échanger des données entre deux programmes que TU PEUX MODIFIER, je te propose
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
     
    //------------------------------------------------------------------------------
    (*                SoLuTions is an Versatile Library for Delphi                 -
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "[Tutoriel] Envoyer des chaînes et structures par PostMessage"      -
     *  Post Number : 7029509                                                      -
     *  Post URL = "http://www.developpez.net/forums/d1286417/environnements-developpement/delphi/tutoriel-envoyer-chaines-structures-postmessage/#post7029509"
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "Redirection des entrées/sorties du process (ping)"                 -
     *  Post Number : 3793892                                                      -
     *  Post URL = "http://www.developpez.net/forums/d453153-2/environnements-developpement/delphi/langage/redirection-entrees-sorties-process-ping/#post3793892"
     *                                                                             -
     *  Copyright ou © ou Copr. "SLT Solutions", (2006)                            -
     *  contributeur : ShaiLeTroll (2012) - Renommage Fichier et Correction XE2    -
     *  contributeur : ShaiLeTroll (2012) - Documentation Insight                  -
     *  contributeur : ShaiLeTroll (2014) - Reprise de la SLT<2012> sous C++Builder XE2/XE3 vers la SLT<2013> sous Delphi XE2
     *                                                                             -
     *                                                                             -
     * Ce logiciel est un programme informatique servant à aider les développeurs  -
     * Delphi avec une bibliothèque polyvalente, adaptable et fragmentable.        -
     *                                                                             -
     * Ce logiciel est régi par la licence CeCILL-C soumise au droit français et   -
     * respectant les principes de diffusion des logiciels libres. Vous pouvez     -
     * utiliser, modifier et/ou redistribuer ce programme sous les conditions      -
     * de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA    -
     * sur le site "http://www.cecill.info".                                       -
     *                                                                             -
     * En contrepartie de l'accessibilité au code source et des droits de copie,   -
     * de modification et de redistribution accordés par cette licence, il n'est   -
     * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,   -
     * seule une responsabilité restreinte pèse sur l'auteur du programme,  le     -
     * titulaire des droits patrimoniaux et les concédants successifs.             -
     *                                                                             -
     * A cet égard  l'attention de l'utilisateur est attirée sur les risques       -
     * associés au chargement,  à l'utilisation,  à la modification et/ou au       -
     * développement et à la reproduction du logiciel par l'utilisateur étant      -
     * donné sa spécificité de logiciel libre, qui peut le rendre complexe à       -
     * manipuler et qui le réserve donc à des développeurs et des professionnels   -
     * avertis possédant  des  connaissances  informatiques approfondies.  Les     -
     * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du      -
     * logiciel à leurs besoins dans des conditions permettant d'assurer la        -
     * sécurité de leurs systèmes et ou de leurs données et, plus généralement,    -
     * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.          -
     *                                                                             -
     * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez      -
     * pris connaissance de la licence CeCILL-C, et que vous en avez accepté les   -
     * termes.                                                                     -
     *                                                                             -
     *----------------------------------------------------------------------------*)
    unit SLT.Common.Winapi.ShellApi;
     
    {$ALIGN ON}
    {$MINENUMSIZE 4}
     
    interface
     
    {*$DEFINE DEBUG_SLT_SEW*}
     
    {$IFDEF MSWINDOWS}
    uses
      Winapi.Windows, Winapi.ShellApi, Winapi.ShlObj, Winapi.Messages, Winapi.ActiveX,
      System.Classes, System.SysUtils, System.Generics.Collections;
    {$ELSE MSWINDOWS}
    {$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTShellExecuteWrapper'}
    {$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTProcessNotification'}
    {$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTCopyDataMessenger'}
    {$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTShellLink'}
    {$ENDIF MSWINDOWS}
     
    type
      { Forward class declarations }
      TSLTShellExecuteWrapper = class;
      TSLTProcessNotification = class;
      TSLTCopyDataMessenger = class;
      TSLTShellLink = class;
     
      /// <summary>TSLTShellExecuteWrapperCallCmdEvent est un évènement lié à la méthode CallCmd qui se produit lorsque des données sont renvoyés par le canaux sortie et erreur par le programme console lancé</summary>
      /// <param name="Output">Chaine du canal de sortie</param>
      /// <param name="Error">Chaine du canal d'erreur</param>
      /// <param name="AbortProcess">Indique si l'on souhaite arreté le programme console</param>
      TSLTShellExecuteWrapperCallCmdEvent = procedure(const Output, Error: string; var AbortProcess: Boolean) of object;
     
      /// <summary>TSLTShellExecuteWrapper encapsule un appel à ShellExecute avec un passage de paramètre via message WM_COPYDATA permettant d'envoyer plus de donnée que l'on pourrait le faire en ligne de commande</summary>
      /// <remarks>TSLTShellExecuteWrapper doit être utilisé de préférence par héritage pour encaspuler la gestion des pointeurs AData
      /// <para>L'Appelant EST TOUJOURS responsable de la libération de AData passé à Execute ou reçu via Receive</para>
      /// <para>TSLTShellExecuteWrapper est une version ouverte du TShaiExecuteProcessWithAutoLogin de la SLT&lt;2009&gt;</para></remarks>
      TSLTShellExecuteWrapper = class(TObject)
      private
        // Membres Privés
        FWindowHandle: HWND;
        FToken: TGUID;
        FCallerHandle: HWND;
        FReceiverHandle: HWND;
        FReady: Boolean;
        FAborted: Boolean;
        FData: Pointer;
        FDataSize: DWORD;
     
        // Types Privés
        type
          TMsgDataOperation = (mdoReceiverNeedData, mdoCallerSendData);
          TMsgHeader = record
            Operation: TMsgDataOperation;
            Token: TGUID;
            DataSize: DWORD;
          end;
     
        // Méthodes Privées
        function Run(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        function RunByCreateProcess(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        function RunByShellExecute(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        function MakeExeName(const AExeName: string): string;
        function MakeParams(AStartWithData: Boolean; const AExtraParam: string = ''): string;
        function ReadParams(): Boolean;
        function SendData(const AData: Pointer; const ADataSize: DWORD): Boolean;
        function ReadData(out AData: Pointer; out ADataSize: DWORD): Boolean;
        function WaitResponse(): Boolean;
        procedure WndProc(var Message: TMessage);
        function TryStrToHWND(const S: string; out Value: HWND): Boolean;
        {$IFDEF DEBUG_SLT_SEW}
        procedure OutputDebugSEW(const Msg: string); inline;
        {$ENDIF DEBUG_SLT_SEW}
      public
        // Types Publiques
        type
          TProcessIdList = System.Generics.Collections.TList<DWORD>;
      private
        // Membres Privés de classe
        class var FProcessIdList: TProcessIdList;
        // Accesseurs de classe
        class function GetProcessIdList(): TProcessIdList; static;
      protected
        // Méthodes Protégées
        procedure AllocData(var AData: Pointer; ADataSize: Integer); virtual;
      public
        // Constructeurs Publiques
        destructor Destroy(); override;
        class destructor Destroy();
     
        // Méthodes Publiques
        class function Execute(const AExeName: string; const AData: Pointer = nil; const ADataSize: DWORD = 0; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        class function Receive(out AData: Pointer; out ADataSize: DWORD): Boolean;
        class function CallCmd(const CmdDirectory, CmdName, CmdParam: string; out ExitCode: Int64; out OutputText: string; out ErrorText: string; Delay: Cardinal = INFINITE; WaitEvent: TSLTShellExecuteWrapperCallCmdEvent = nil; PipeMaxSize: Cardinal = 0): Boolean;
     
        // Propriétés Publiques
        class property ProcessIdList: TProcessIdList read GetProcessIdList;
      end;
     
      /// <summary>TSLTProcessNotifyToken identifie une notification gérée par TSLTProcessNotification</summary>
      TSLTProcessNotifyToken = UINT;
      /// <summary>TSLTProcessNotifyListener identifie une cible écoutant les notifications gérées par TSLTProcessNotification</summary>
      TSLTProcessNotifyListener = HWND;
     
      /// <summary>TSLTProcessNotifyEvent est l'évènement émis par TSLTProcessNotification</summary>
      TSLTProcessNotifyEvent = procedure(Sender: TObject; Token: TSLTProcessNotifyToken) of object;
     
      /// <summary>TSLTProcessNotification gère un échange inter-processus</summary>
      TSLTProcessNotification = class(TObject)
      private
        // Types Privés
        type
          TTokenInfo = class(TObject)
          public
            type
              TListenerList = System.Generics.Collections.TList<TSLTProcessNotifyListener>;
          strict private
            FToken: TSLTProcessNotifyToken;
            FListeners: TListenerList;
          public
            // Constructeurs Publiques
            constructor Create(AToken: TSLTProcessNotifyToken);
            destructor Destroy(); override;
            // Propriétés Publiques
            property Token: TSLTProcessNotifyToken read FToken;
            property Listeners: TListenerList read FListeners;
          end;
          TTokenList = System.Generics.Collections.TObjectList<TTokenInfo>;
          TNotificationMap = System.Generics.Collections.TDictionary<string, TSLTProcessNotifyToken>;
      private
        // Membres Privés
        FListener: TSLTProcessNotifyListener;
        FListenerName: string;
        FNotifications: TNotificationMap;
        FOnNotify: TSLTProcessNotifyEvent;
        FTokens: TTokenList;
        // Méthodes Privées
        procedure WndProc(var Message: TMessage);
        function GetListener(): TSLTProcessNotifyListener;
        function FindToken(AToken: TSLTProcessNotifyToken): TTokenInfo;
        function GetListenerName(): string;
        procedure SetListenerName(const Value: string);
      public
        // Constructeurs Publiques
        constructor Create();
        destructor Destroy(); override;
     
        // Méthodes Publiques
        function RegisterNotification(const ANotificationName: string): TSLTProcessNotifyToken;
        function AddListener(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
        function AddListenerByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
        procedure NotifyListeners(AToken: TSLTProcessNotifyToken); overload;
        function NotifyListeners(const ANotificationName: string): TSLTProcessNotifyToken; overload;
        function Notify(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
        function NotifyByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
        function Listen(): Boolean;
     
        // Propriétés Publiques
        property Listener: TSLTProcessNotifyListener read GetListener;
        property ListenerName: string read GetListenerName write SetListenerName;
        property OnNotify: TSLTProcessNotifyEvent read FOnNotify write FOnNotify;
      end;
     
      /// <summary>TSLTCopyDataMessengerDataEvent est l'évènement émis par TSLTCopyDataMessenger lorsqu'il y a de données à lire</summary>
      TSLTCopyDataMessengerDataEvent = function(Sender: TObject; DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean of object;
     
      /// <summary>TSLTCopyDataMessenger gère un échange de données inter-processus via le message WM_COPYDATA</summary>
      TSLTCopyDataMessenger = class(TObject)
      private
        // Membres Privés
        FListenerHandle: HWND;
        FListenerName: string;
        FRecipientHandle: HWND;
        FRecipientName: string;
        FRawData: COPYDATASTRUCT;
        FOnDataAvailable: TSLTCopyDataMessengerDataEvent;
     
        // Accesseurs
        function GetListenerHandle(): HWND;
        function GetListenerName(): string;
        procedure SetListenerName(const Value: string);
        function GetRecipientName(): string;
        procedure SetRecipientName(const Value: string);
     
        // Méthodes Privées
        procedure WndProc(var Message: TMessage);
        function DoDataAvailable(DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean;
     
      public
        // Constructeurs Publiques
        destructor Destroy(); override;
     
        // Méthodes Publiques
        procedure BeginWrite();
        procedure WriteInteger(const Value: Integer);
        procedure WriteString(const Value: string);
        procedure WriteBuffer(const Data: Pointer; const DataLen: NativeUInt);
        function EndWrite(): Boolean;
        procedure CancelWrite();
     
        function Listen(): Boolean;
        function ReadInteger(const Data: Pointer; out Value: Integer): Integer;
        function ReadString(const Data: Pointer; out Value: string): Integer;
        function Seek(const Data: Pointer; Offset: NativeUInt): Pointer;
     
        // Propriétés Publiques
        property ListenerHandle: HWND read GetListenerHandle;
        property ListenerName: string read GetListenerName write SetListenerName;
        property RecipientHandle: HWND read FRecipientHandle write FRecipientHandle;
        property RecipientName: string read GetRecipientName write SetRecipientName;
        property OnDataAvailable: TSLTCopyDataMessengerDataEvent read FOnDataAvailable write FOnDataAvailable;
      end;
     
      /// <summary>TSLTShellLink encapsule l'utilisation de l'interface IShellLink</summary>
      TSLTShellLink = class(TObject)
      public
        class function ExtractTarget(const AShellLinkFileName: TFileName): TFileName;
      end;
     
    implementation
     
    {$IFDEF DEBUG_SLT_SEW}
    uses SLT.Common.Tracing;
    {$ENDIF DEBUG_SLT_SEW}
     
    const
      PARAM_START_WITH_DATA = 'START_WITH_DATA'; // Do not localize
      PARAM_START_WITH_DATA_CALLER = 'H'; // Do not localize
      PARAM_START_WITH_DATA_TOKEN = 'T'; // Do not localize
     
    { TSLTShellExecuteWrapper }
     
     
    //------------------------------------------------------------------------------
    procedure TSLTShellExecuteWrapper.AllocData(var AData: Pointer; ADataSize: Integer);
    begin
      GetMem(AData, ADataSize);
    end;
     
    {* -----------------------------------------------------------------------------
    la fonction CallCmd permet de lancer un programme console, tout en récupérant en quasi temps-réel le contenu devant normalement s'y afficher
    @param CmdDirectory Dossier contenant le Fichier CmdName
    @param CmdName programme console à executer
    @param CmdParam paramètres de la ligne de commande
    @param ExitCode Code de Sortie renvoyé par le programme console, -1 si non récupéré
    @param OutputText chaine contenant tout ce qui aurait du s'afficher (canal sortie)
    @param ErrorText chaine contenant tout ce qui a été signalé comme erreurs (canal erreur)
    @param Delay indique le temps entre chaque cycle de lecture des canaux, détermine la fréquence de lancement de WaitEvent, par défaut, cela attend que le programme console se termine
    @param WaitEvent procédure à lancer lorsque le Delay est écoulé, Output et Error contiennent les derniers éléments envoyés par le programme console sur les canaux depuis le dernier délai, AbortProcess indique si la processus doit être arrêté
    @param PipeMaxSize défini la taille maximal que l'on lit à chaque chaque cycle de lecture des canaux, si zéro, taille non limitée par défaut
    @return Indique si le programme a été lancé
    ------------------------------------------------------------------------------ }
    class function TSLTShellExecuteWrapper.CallCmd(const CmdDirectory, CmdName, CmdParam: string; out ExitCode: Int64; out OutputText: string; out ErrorText: string; Delay: Cardinal = INFINITE; WaitEvent: TSLTShellExecuteWrapperCallCmdEvent = nil; PipeMaxSize: Cardinal = 0): Boolean;
    var
      StartupInfo: TStartupInfo;
      ProcessInfo: TProcessInformation;
      CmdLine: string; // utile pour le débogage
      SecurityAttr : TSecurityAttributes;
      hReadPipeInput, hWritePipeInput: NativeUInt;
      hReadPipeOutput, hWritePipeOutput: NativeUInt;
      hReadPipeError, hWritePipeError: NativeUInt;
      lpCurrentDirectory: PChar;
      Terminated: Boolean;
      AbortProcess: Boolean;
      HandleFunctionProcess: Cardinal;
     
      function ReadPipe(Handle: Cardinal; out Buf: string): Boolean;
      const
        MAX_INT: Cardinal = MaxInt;
      var
        PipeSize: Cardinal;
        PipeToRead, PipeReaded: Cardinal;
        PipeBuf: array of AnsiChar;
        AnsiBuf: AnsiString;
      begin
        PipeSize := GetFileSize(Handle, nil); // On oublie si cela dépasse 2Go ... normalement c'est 4Ko
        if (PipeMaxSize > 0) and (PipeSize > PipeMaxSize) then
          PipeToRead := PipeMaxSize
        else
          PipeToRead := PipeSize;
     
        Result := PipeToRead > 0;
        if Result then
        begin
          SetLength(PipeBuf, PipeToRead);
          ZeroMemory(@PipeBuf[0], PipeToRead);
          ReadFile(Handle, PipeBuf[0], PipeToRead, PipeReaded, nil);
     
          SetLength(AnsiBuf, PipeToRead);
          OemToAnsi(@PipeBuf[0], @AnsiBuf[1]);
          Buf := string(AnsiBuf);
        end;
      end;
     
      procedure ReadPipes();
      var
        DeltaOutputText: string;
        DeltaErrorText: string;
      begin
        if ReadPipe(hReadPipeOutput, DeltaOutputText) then
          OutputText := OutputText + DeltaOutputText;
        if ReadPipe(hReadPipeError, DeltaErrorText) then
          ErrorText := ErrorText + DeltaErrorText;
        try
          if Assigned(WaitEvent) then
            WaitEvent(DeltaOutputText, DeltaErrorText, AbortProcess);
        except
          on E: Exception do
            OutputDebugString(PChar(Format('s.CallCmd.ReadPipes.WaitEvent - "%s" : "%s"', [Self.ClassName(), E.ClassName(), E.Message])));
        end;
      end;
     
    begin
      (*
      Result := True;
      OutputText := 'Dummy Output';
      ErrorText := 'Dummy Error';
      ErrorCode := 0;
      Exit;
      *)
      OutputText := '';
      ErrorText := '';
      try
        SecurityAttr.nLength := SizeOf(TSecurityAttributes);
        SecurityAttr.lpSecurityDescriptor := nil;
        SecurityAttr.bInheritHandle := True;
        if CreatePipe(hReadPipeInput, hWritePipeInput, @SecurityAttr, 0) and
          CreatePipe(hReadPipeOutput, hWritePipeOutput, @SecurityAttr, 0) and
          CreatePipe(hReadPipeError, hWritePipeError, @SecurityAttr, 0) then
        begin
          try
            ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); // GetStartupInfo(StartupInfo);
            StartupInfo.cb := SizeOf(StartupInfo);
            StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; // Active wShowWindow et hStdOutput/hStdError
            StartupInfo.wShowWindow := SW_HIDE;
            StartupInfo.hStdInput := hReadPipeInput;
            StartupInfo.hStdOutput := hWritePipeOutput;
            StartupInfo.hStdError := hWritePipeError;
            ZeroMemory(@ProcessInfo, SizeOf(ProcessInfo));
     
            if CmdDirectory <> '' then
            begin
              CmdLine := Format('"%s%s" %s', [IncludeTrailingPathDelimiter(CmdDirectory), CmdName, CmdParam]);
              lpCurrentDirectory := PChar(CmdDirectory);
            end
            else
            begin
              CmdLine := Format('%s %s', [CmdName, CmdParam]);
              lpCurrentDirectory := nil;
            end;
     
            Result := CreateProcess(nil, PChar(CmdLine), @SecurityAttr, @SecurityAttr, True, 0, nil, lpCurrentDirectory, StartupInfo, ProcessInfo);
            if Result then
            begin
              try
                Terminated := False;
                AbortProcess := False;
                while not Terminated do
                begin
                  case WaitForSingleObject(ProcessInfo.hProcess, Delay) of
                    WAIT_OBJECT_0 :
                      begin
                        ReadPipes();
                        Terminated := True;
                      end;
                    WAIT_ABANDONED : Terminated := True;
                    WAIT_TIMEOUT :
                      begin
                        ReadPipes();
                        Terminated := Delay = INFINITE;
                      end;
                    WAIT_FAILED: Abort;
                  else
                    Terminated := True;
                  end;
     
                  if AbortProcess then
                  begin
                   HandleFunctionProcess := OpenProcess(PROCESS_TERMINATE, False, ProcessInfo.dwProcessId);
                   if HandleFunctionProcess > 0 then
                   begin
                     TerminateProcess(HandleFunctionProcess, 0);
                     CloseHandle(HandleFunctionProcess);
                   end;
                  end;
                end;
     
                TULargeInteger(ExitCode).HighPart := 0;
                if not GetExitCodeProcess(ProcessInfo.hProcess, TULargeInteger(ExitCode).LowPart) then
                  ExitCode := -1;
              finally
                CloseHandle(ProcessInfo.hThread);
                CloseHandle(ProcessInfo.hProcess); // The handles for both the process and the main thread must be closed through calls to CloseHandle
              end;
            end;
          finally
            CloseHandle(hReadPipeInput);
            CloseHandle(hWritePipeInput);
            CloseHandle(hReadPipeOutput);
            CloseHandle(hWritePipeOutput);
            CloseHandle(hReadPipeError);
            CloseHandle(hWritePipeError);
          end;
        end
        else
          raise Exception.Create('Impossible de créer les Pipes');
      except
        on E: Exception do
        begin
          OutputDebugString(PChar(Format('%s.CallCmd Error %s, Message : %s', [Self.ClassName(), E.ClassName(), E.Message])));
          raise;
        end;
      end;
    end;
     
     
    //------------------------------------------------------------------------------
    class destructor TSLTShellExecuteWrapper.Destroy();
    begin
      FreeAndNil(FProcessIdList);
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTShellExecuteWrapper.Destroy();
    begin
      if FWindowHandle <> 0 then
      begin
        System.Classes.DeallocateHWnd(FWindowHandle);
        FWindowHandle := 0;
      end;
     
      inherited Destroy();
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTShellExecuteWrapper.Execute(const AExeName: string; const AData: Pointer = nil; const ADataSize: DWORD = 0; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
    var
      StartWithData: Boolean;
    begin
      Result := False;
     
      with Self.Create() do
      try
        StartWithData := Assigned(AData) and (ADataSize > 0);
        if Run(AExeName, StartWithData, AShowCmd, AExtraParam) then
        begin
          if StartWithData then
            Result := SendData(AData, ADataSize)
          else
            Result := True;
        end
        else
          raise System.SysUtils.EOSError.Create(System.SysUtils.SysErrorMessage(Winapi.Windows.GetLastError()));
      finally
        Free();
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTShellExecuteWrapper.GetProcessIdList(): TProcessIdList;
    begin
      if not Assigned(FProcessIdList) then
        FProcessIdList := TProcessIdList.Create();
     
      Result := FProcessIdList;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.MakeExeName(const AExeName: string): string;
    var
      ModuleFileName: array[0..MAX_PATH-1] of Char;
    begin
      Result := AExeName;
      // Si nom complet, exploite directement ce chemin
      // Si juste nom du fichier, utilise le répertoire de l'appelant !
      if ExtractFileDrive(AExeName) = '' then // gère <lecteur>:\<dossier>' aussi bien que '\\<serveur>\<nom_partagé>'.
      begin
        GetModuleFileName(0, ModuleFileName, MAX_PATH); // 0 c'est pour l'EXE même si depuis une DLL, avec HInstance cela fournirait le nom de la DLL
        Result := ExtractFilePath(ModuleFileName) + ExtractFileName(AExeName);
      end;
    end;
     
    //------------------------------------------------------------------------------
    {$IFDEF DEBUG_SLT_SEW}
    procedure TSLTShellExecuteWrapper.OutputDebugSEW(const Msg: string);
    begin
      TSLTDebugLogger.OutputDebugString('[SLT.SEW]', Msg);
    end;
    {$ENDIF DEBUG_SLT_SEW}
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.MakeParams(AStartWithData: Boolean; const AExtraParam: string = ''): string;
    begin
      if AStartWithData then
      begin
        FWindowHandle := AllocateHWnd(WndProc);
        FCallerHandle := FWindowHandle;
        System.SysUtils.CreateGUID(FToken);
        Result := Format('/%s -%s0x%s -%s%s', [PARAM_START_WITH_DATA, PARAM_START_WITH_DATA_CALLER, IntToHex(FCallerHandle, SizeOf(FCallerHandle) * 2), PARAM_START_WITH_DATA_TOKEN, GUIDToString(FToken)]);
        if AExtraParam <> '' then
          Result := AExtraParam + ' ' + Result;
      end
      else
        Result := '';
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.ReadData(out AData: Pointer; out ADataSize: DWORD): Boolean;
    begin
      Result := False;
     
      // Attend que le programme appelant fournisse les données
      if WaitResponse() then
      begin
        AData := FData;
        ADataSize := FDataSize;
        Result := True;
     
        FData := nil;
        FDataSize := 0;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.ReadParams(): Boolean;
    var
      HandleText, TokenText: string;
      MsgDataHeader: TMsgHeader;
      RawData: COPYDATASTRUCT;
    begin
      Result := False;
      FReady := False;
     
      if FindCmdLineSwitch(PARAM_START_WITH_DATA) then
      begin
        if FindCmdLineSwitch(PARAM_START_WITH_DATA_CALLER, HandleText, True, [clstValueAppended]) and TryStrToHWND(HandleText, FCallerHandle) and (FCallerHandle <> 0) then
        begin
          if FindCmdLineSwitch(PARAM_START_WITH_DATA_TOKEN, TokenText, True, [clstValueAppended]) then
          begin
            try
              FToken := StringToGUID(TokenText);
     
              FWindowHandle := System.Classes.AllocateHWnd(WndProc);
              FReceiverHandle := FWindowHandle;
     
              MsgDataHeader.Operation := mdoReceiverNeedData;
              MsgDataHeader.Token := FToken;
              MsgDataHeader.DataSize := 0;
     
              RawData.dwData := 0;
              RawData.cbData := SizeOf(MsgDataHeader);
              RawData.lpData := @MsgDataHeader;
     
              if SendMessage(FCallerHandle, WM_COPYDATA, FReceiverHandle, LPARAM(@RawData)) <> 0 then
                Result := True;
            except
              on E: Exception do
              begin
                {$IFDEF DEBUG_SLT_SEW}
                OutputDebugSEW(Format('Exception %s : "%s"', [E.ClassName(), E.Message]));
                {$ENDIF DEBUG_SLT_SEW};
              end;
            end;
          end;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTShellExecuteWrapper.Receive(out AData: Pointer; out ADataSize: DWORD): Boolean;
    begin
      with Self.Create() do
      try
        Result := ReadParams() and ReadData(AData, ADataSize);
      finally
        Free();
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.Run(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
    begin
      // This system metric is used in a Terminal Services environment.
      // If the calling process is associated with a Terminal Services client session, the return value is nonzero.
      // If the calling process is associated with the Terminal Server console session, the return value is 0.
      // CreateProcess permet d'éviter un avertissement lié à l'emplacement du fichier
      // Sur un serveur via Terminal Server, l'emplacement devrait être toujours exprimé sous la forme d'un chemin réseau UNC
      // Sur un poste utilisateur, mieux vaut se limiter à un accès local même si rien n'empêche d'accéder par réseau à une ressource externe
      if LongBool(GetSystemMetrics(SM_REMOTESESSION)) then
        Result := RunByCreateProcess(AExeName, AStartWithData, AShowCmd, AExtraParam)
      else
        Result := RunByShellExecute(AExeName, AStartWithData, AShowCmd, AExtraParam);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.RunByCreateProcess(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
    var
      StartupInfo: TStartupInfo;
      ProcessInfo: TProcessInformation;
      SecurityAttr : TSecurityAttributes;
      ProcessFile: TFileName;
      CmdLine, CmdParam, CmdDirectory: string;
    begin
      try
        SecurityAttr.nLength := SizeOf(TSecurityAttributes);
        SecurityAttr.lpSecurityDescriptor := nil;
        SecurityAttr.bInheritHandle := True;
     
        ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); // GetStartupInfo(StartupInfo);
        StartupInfo.cb := SizeOf(StartupInfo);
        StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
        StartupInfo.wShowWindow := AShowCmd;
        ProcessFile := MakeExeName(AExeName);
        CmdParam := MakeParams(AStartWithData, AExtraParam);
        CmdLine := Format('"%s" %s', [AExeName, CmdParam]);
        CmdDirectory := ExtractFileDir(AExeName);
        Result := CreateProcess(nil, PChar(CmdLine), @SecurityAttr, @SecurityAttr, True, 0, nil, PChar(CmdDirectory), StartupInfo, ProcessInfo);
        if Result then
        begin
          // Mémorise tous les processus lancés par TSLTShellExecuteWrapper
          ProcessIdList.Add(ProcessInfo.dwProcessId);
          // Je ne dois pas conserver le process ouvert, cela ne ferme que les pointeurs sur le process mais celui reste bien actif
          // MSDN : "Handles in PROCESS_INFORMATION must be closed with CloseHandle when they are no longer needed."
          // Ne pas confondre CloseHandle et TerminateProcess !
          // En Citrix, cela semble conserver le fichier vérouillé (en local,
          CloseHandle(ProcessInfo.hThread);
          CloseHandle(ProcessInfo.hProcess); // The handles for both the process and the main thread must be closed through calls to CloseHandle
        end;
      except
        on E: Exception do
        begin
          OutputDebugString(PChar(Format('TSLTShellExecuteWrapper.RunByCreateProcess Error %s, Message : %s', [E.ClassName, E.Message])));
          raise;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.RunByShellExecute(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
    var
      ShellFile: TFileName;
      ExecuteInfo: TShellExecuteInfo;
    begin
      ShellFile := MakeExeName(AExeName);
      with ExecuteInfo do
      begin
        cbSize := Sizeof(ExecuteInfo);
        fMask := SEE_MASK_NOCLOSEPROCESS;
        Wnd := 0;
        lpVerb := PChar('open');
        lpFile := PChar(ShellFile);
        lpParameters := PChar(MakeParams(AStartWithData, AExtraParam));
        lpDirectory := PChar(ExtractFileDir(ShellFile));
        nShow := AShowCmd;
      end;
     
      Result := ShellExecuteEx(@ExecuteInfo);
      if Result and (ExecuteInfo.hProcess > 0) then
      begin
        // Mémorise tous les processus lancés par TSLTShellExecuteWrapper
        ProcessIdList.Add(GetProcessId(ExecuteInfo.hProcess));
        // Nettoyage !
        CloseHandle(ExecuteInfo.hProcess); // The calling application is responsible for closing the handle when it is no longer needed.
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.SendData(const AData: Pointer; const ADataSize: DWORD): Boolean;
    var
      MsgDataHeader: TMsgHeader;
      RawData: COPYDATASTRUCT;
      Buf: Pointer;
      BufCursor: PByte;
      BufSize: DWORD;
    begin
      Result := False;
     
      // Attend que le programme appelé réclame les données
      if WaitResponse() then
      begin
        MsgDataHeader.Operation := mdoCallerSendData;
        MsgDataHeader.Token := FToken;
        MsgDataHeader.DataSize := ADataSize;
     
        BufSize := SizeOf(MsgDataHeader) + ADataSize;
        GetMem(Buf, BufSize);
        try
          BufCursor := Buf;
          Move(MsgDataHeader, BufCursor^, SizeOf(MsgDataHeader));
          Inc(BufCursor, SizeOf(MsgDataHeader));
          Move(AData^, BufCursor^, ADataSize);
     
          RawData.dwData := 0;
          RawData.cbData := BufSize;
          RawData.lpData := Buf;
     
          if SendMessage(FReceiverHandle, WM_COPYDATA, FCallerHandle, LPARAM(@RawData)) <> 0 then
            Result := True;
        finally
          FreeMem(Buf);
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.TryStrToHWND(const S: string; out Value: HWND): Boolean;
    begin
      // Il existe UIntToStr mais pas StrToUInt !!!
    {$IFDEF CPUX86}
      Result := TryStrToInt(S, Integer(Value))
    {$ENDIF CPUX86}
    {$IFDEF CPUX64}
      Result := TryStrToInt64(S, Int64(Value));
    {$ENDIF CPUX64}
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.WaitResponse(): Boolean;
    var
      SleepCount: Cardinal;
      Msg: TMsg;
    begin
      SleepCount := 0;
     
      // Attend que le programme appelant fournisse les identifiants
      repeat
        if SleepCount < 5000 then
        begin
          Sleep(1); // Environ 1.995 ms dont au plus 10s d'attente
          Inc(SleepCount);
          if PeekMessage(Msg, FWindowHandle, WM_COPYDATA, WM_COPYDATA, PM_REMOVE) then
          begin
            TranslateMessage(Msg);
            DispatchMessage(Msg); // -> WndProc
          end;
        end
        else
          FAborted := True;
     
      until FReady or FAborted;
     
      Result := FReady;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTShellExecuteWrapper.WndProc(var Message: TMessage);
    var
      RawData: PCOPYDATASTRUCT;
      MsgDataHeader: TMsgHeader;
      BufCursor: PByte;
    begin
      if Message.Msg = WM_COPYDATA then
      begin
        RawData := PCOPYDATASTRUCT(Message.LParam);
        if Assigned(RawData) then
        begin
          if RawData^.cbData >= SizeOf(TMsgHeader) then
          begin
            Move(RawData^.lpData^, MsgDataHeader, SizeOf(TMsgHeader));
     
            case MsgDataHeader.Operation of
     
              mdoReceiverNeedData :
              begin
                FReceiverHandle := HWND(Message.WParam);
                FReady := (FReceiverHandle <> 0) and IsEqualGUID(FToken, MsgDataHeader.Token);
              end;
     
              mdoCallerSendData :
              begin
                if IsEqualGUID(FToken, MsgDataHeader.Token) and (FCallerHandle = HWND(Message.WParam)) then
                begin
                  FReady := MsgDataHeader.DataSize > 0;
                  if FReady then
                  begin
                    BufCursor := RawData^.lpData;
                    Inc(BufCursor, SizeOf(MsgDataHeader));
     
                    AllocData(FData, MsgDataHeader.DataSize);
                    Move(BufCursor^, FData^, MsgDataHeader.DataSize);
                    FDataSize := MsgDataHeader.DataSize;
                  end
                end;
              end;
            end;
     
            if FReady then
            begin
              Message.Result := 1;
            end
            else
            begin
              Message.Result := 0;
              FAborted := True;
            end;
          end;
        end;
      end
      else
        Message.Result := DefWindowProc(FWindowHandle, Message.Msg, Message.WParam, Message.LParam);
    end;
     
    { TSLTProcessNotification }
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.AddListener(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
    var
      TokenInfo: TTokenInfo;
    begin
      Result := False;
     
      TokenInfo := FindToken(AToken);
      if Assigned(TokenInfo) and not TokenInfo.Listeners.Contains(AListener) then
      begin
        TokenInfo.Listeners.Add(AListener);
        Result := True;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.AddListenerByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
    var
      ListenerHWND: HWND;
    begin
      ListenerHWND := FindWindow(nil, PChar(AListenerName));
      if ListenerHWND <> 0 then
      begin
        Result := AddListener(ListenerHWND, AToken);
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    constructor TSLTProcessNotification.Create();
    begin
      inherited Create();
     
      FTokens := TTokenList.Create(True);
      FNotifications := TNotificationMap.Create();
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTProcessNotification.Destroy();
    begin
      FreeAndNil(FNotifications);
      FreeAndNil(FTokens);
     
      if FListener <> 0 then
      begin
        System.Classes.DeallocateHWnd(FListener);
        FListener := 0;
      end;
     
      inherited Destroy();
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.FindToken(AToken: TSLTProcessNotifyToken): TTokenInfo;
    var
      I: Integer;
    begin
      for I := 0 to FTokens.Count - 1 do
      begin
        Result := FTokens.Items[I];
        if Result.Token = AToken then
          Exit;
      end;
     
      Result := nil;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.GetListener(): TSLTProcessNotifyListener;
    begin
      if FListener = 0 then
        FListener := AllocateHWnd(WndProc);
     
      Result := FListener;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.GetListenerName(): string;
    var
      WindowText: array[0..MAX_PATH-1] of Char;
    begin
      if FListener <> 0 then
        if GetWindowText(FListener, WindowText, MAX_PATH) > 0 then
          FListenerName := WindowText;
     
      Result := FListenerName;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.Listen(): Boolean;
    begin
      Result := Listener <> 0;
      if Result then
        SetWindowText(FListener, PChar(FListenerName));
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.Notify(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
    begin
      Result := SendMessage(AListener, AToken, 0, 0) <> 0;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.NotifyByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
    begin
      Result := AddListenerByName(AListenerName, AToken);
      NotifyListeners(AToken);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.NotifyListeners(const ANotificationName: string): TSLTProcessNotifyToken;
    begin
      Result := RegisterNotification(ANotificationName);
      NotifyListeners(Result);
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTProcessNotification.NotifyListeners(AToken: TSLTProcessNotifyToken);
    var
      TokenInfo: TTokenInfo;
      I: Integer;
    begin
      TokenInfo := FindToken(AToken);
      if Assigned(TokenInfo) then
        with TokenInfo.Listeners do
          for I := 0 to Count - 1 do
            Self.Notify(Items[I], AToken);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTProcessNotification.RegisterNotification(const ANotificationName: string): TSLTProcessNotifyToken;
    begin
      if not FNotifications.TryGetValue(ANotificationName, Result) then
      begin
        Result := RegisterWindowMessage(PChar(ANotificationName));
        FNotifications.Add(ANotificationName, Result);
      end;
     
      if not Assigned(FindToken(Result)) then
        FTokens.Add(TTokenInfo.Create(Result));
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTProcessNotification.SetListenerName(const Value: string);
    begin
      FListenerName := Value;
      if FListener <> 0 then
        SetWindowText(FListener, PChar(FListenerName));
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTProcessNotification.WndProc(var Message: TMessage);
    begin
      if not (Message.Msg in [WM_DESTROY, WM_NCDESTROY, WM_SETTEXT, WM_GETTEXT]) and Assigned(FTokens) and Assigned(FindToken(Message.Msg)) then
      begin
        if Assigned(FOnNotify) then
          FOnNotify(Self, Message.Msg);
      end
      else
        Message.Result := DefWindowProc(FListener, Message.Msg, Message.WParam, Message.LParam);
    end;
     
    { TSLTProcessNotification.TTokenInfo }
     
    //------------------------------------------------------------------------------
    constructor TSLTProcessNotification.TTokenInfo.Create(AToken: TSLTProcessNotifyToken);
    begin
      inherited Create();
     
      FToken := AToken;
      FListeners := TListenerList.Create();
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTProcessNotification.TTokenInfo.Destroy();
    begin
      FreeAndNil(FListeners);
     
      inherited Destroy();
    end;
     
    { TSLTCopyDataMessenger }
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.BeginWrite();
    begin
      CancelWrite();
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.CancelWrite();
    begin
      FreeMem(FRawData.lpData);
      ZeroMemory(@FRawData, SizeOf(FRawData));
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTCopyDataMessenger.Destroy();
    begin
      CancelWrite();
     
      if FListenerHandle <> 0 then
      begin
        DeallocateHWnd(FListenerHandle);
        FListenerHandle := 0;
      end;
     
      inherited Destroy();
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.DoDataAvailable(DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean;
    begin
      Result := False;
      if Assigned(FOnDataAvailable) then
        Result := FOnDataAvailable(Self, DataSender, Data, DataLen);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.EndWrite(): Boolean;
    begin
      // Le Handle d'écoute et de lecture est considéré comme le Handle émetteur (correspond à DataSender dans TSLTCopyDataMessengerReadEvent)
      // Le Handle d'écriture, dans cette terminologie, est considéré comme le Handle récepteur (DataRecipient)
      Result := SendMessage(FRecipientHandle, WM_COPYDATA, WPARAM(FListenerHandle), LPARAM(@FRawData)) <> 0;
     
      CancelWrite();
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.GetListenerHandle(): HWND;
    begin
      if FListenerHandle = 0 then
        FListenerHandle := AllocateHWnd(WndProc);
     
      Result := FListenerHandle;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.GetListenerName(): string;
    var
      WindowText: array[0..MAX_PATH-1] of Char;
    begin
      if FListenerHandle <> 0 then
        if GetWindowText(FListenerHandle, WindowText, MAX_PATH) > 0 then
          FListenerName := WindowText;
     
      Result := FListenerName;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.GetRecipientName(): string;
    var
      WindowText: array[0..MAX_PATH-1] of Char;
    begin
      if FRecipientHandle <> 0 then
        if GetWindowText(FRecipientHandle, WindowText, MAX_PATH) > 0 then
          FRecipientName := WindowText;
     
      Result := FRecipientName;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.Listen(): Boolean;
    begin
      Result := ListenerHandle <> 0;
      if Result then
        SetWindowText(FListenerHandle, PChar(FListenerName));
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.ReadInteger(const Data: Pointer; out Value: Integer): Integer;
    begin
      Result := -1;
      if not IsBadReadPtr(Data, SizeOf(Value)) then
      begin
        Value := PInteger(Data)^;
        Result := SizeOf(Value);
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.ReadString(const Data: Pointer; out Value: string): Integer;
    var
      Len, IntSize, StrSize: Integer;
      Cursor: PByte;
    begin
      Result := -1;
      Len := 0;
      IntSize := ReadInteger(Data, Len);
      if IntSize > 0 then
      begin
        Result := IntSize;
        if Len > 0 then
        begin
          Cursor := Data;
          Inc(Cursor, IntSize);
          SetLength(Value, Len);
          StrSize := Len * SizeOf(Char); // gère que la table BMP de UTF-16
          Move(Cursor^, Value[1], StrSize);
          Inc(Result, StrSize);
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTCopyDataMessenger.Seek(const Data: Pointer; Offset: NativeUInt): Pointer;
    begin
      Result := Pointer(NativeUInt(Data) + Offset);
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.SetListenerName(const Value: string);
    begin
      // Change le nom pour le handle d'écoute
      FListenerName := Value;
      if FListenerHandle <> 0 then
        SetWindowText(FListenerHandle, PChar(FListenerName));
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.SetRecipientName(const Value: string);
    begin
      // Cherche par son nom le handle de destination
      FRecipientName := Value;
      FRecipientHandle := FindWindow(nil, PChar(FRecipientName))
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.WndProc(var Message: TMessage);
    var
      PRawData: PCOPYDATASTRUCT;
    begin
      if Message.Msg = WM_COPYDATA then
      begin
        PRawData := PCOPYDATASTRUCT(Message.LParam);
        Message.Result := 0;
        if Assigned(PRawData) and (PRawData^.cbData > 0) then
          if DoDataAvailable(HWND(Message.WParam), PRawData^.lpData, PRawData^.cbData) then
            Message.Result := 1;
      end
      else
        Message.Result := DefWindowProc(FListenerHandle, Message.Msg, Message.WParam, Message.LParam);
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.WriteBuffer(const Data: Pointer; const DataLen: NativeUInt);
    var
      Position: Integer;
      Cursor: PByte;
    begin
      Position := FRawData.cbData;
      Inc(FRawData.cbData, DataLen);
     
      if Position > 0 then
        ReallocMem(FRawData.lpData, FRawData.cbData)
      else
        GetMem(FRawData.lpData, FRawData.cbData);
     
      Cursor := FRawData.lpData;
      Inc(Cursor, Position);
      Move(Data^, Cursor^, DataLen);
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.WriteInteger(const Value: Integer);
    begin
      WriteBuffer(@Value, SizeOf(Value));
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTCopyDataMessenger.WriteString(const Value: string);
    var
      Len, Size: Integer;
    begin
      Len := Length(Value);
      WriteInteger(Len);
     
      if Len > 0 then
      begin
        Size := Len * SizeOf(Char); // gère que la table BMP de UTF-16
        WriteBuffer(PChar(Value), Size);
      end;
    end;
     
    { TSLTShellLink }
     
    //------------------------------------------------------------------------------
    class function TSLTShellLink.ExtractTarget(const AShellLinkFileName: TFileName): TFileName;
    // Voir la fonction cachée "GetFileNameFromLink" dans Vcl.ExtDlgs
    // Ne pase inclure Winapi.Ole2 qui contient IID_IPersistFile, cela devient trop pénible les conflits entre TGUID de Delphi et TGUID de Winapi.Ole2
    const
      IID_IPersistFile: TGUID = '{0000010B-0000-0000-C000-000000000046}';
    var
      LResult: HRESULT;
      LSHellLink: IShellLink;
      LPersistFile: IPersistFile;
      LFindData: TWin32FindData;
      FileName: array[0..MAX_PATH - 1] of Char;
    begin
      Result := '';
      LResult := CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLinkW, LShellLink);
      if LResult = S_OK then
      begin
        if Supports(LShellLink, IID_IPersistFile, LPersistFile) then
        begin
          LResult := LPersistFile.Load(PChar(AShellLinkFileName), STGM_READ);
          if LResult = S_OK then
          begin
            LResult := LSHellLink.GetPath(FileName, MAX_PATH, LFindData, SLGP_UNCPRIORITY);
            if LResult = S_OK then
              Result := Trim(FileName);
          end;
        end;
      end;
    end;
     
    end.
    et une version en TCP

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    //------------------------------------------------------------------------------
    (*                SoLuTions is an Versatile Library for Delphi                 -
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "Socket sans Form"                                                  -
     *  Post Number : post6590226                                                  -
     *  Post URL = "http://www.developpez.net/forums/d1202233/environnements-developpement/delphi/debutant/socket-form/#post6590226"
     *                                                                             -
     *  Version alternative publiée sur "www.phidels.com"                          -
     *  Post : "TClientSocket et IRC"                                              -
     *  Post URL = "http://www.phidels.com/php/forum/forum.php3?forumtable=svgposts1&mode=showpost&postid=111400"
     *                                                                             -
     *  Copyright ou © ou Copr. "SLT Solutions", (2006)                            -
     *  contributeur : ShaiLeTroll (2009) - Reprise de la SLT<2006> sous Delphi 7 vers la SLT<2009> sous C++Builder 2007
     *  contributeur : ShaiLeTroll (2015) - Reprise de la SLT<2009> sous C++Builder 2007 vers la SLT<2013> sous Delphi XE2
     *  Remarque : l'utilisation du TServerSocket est volontaire, car TTCPServer (Web.Win.Sockets) a été retiré dans la version XE6 !
     *                                                                             -
     *                                                                             -
     * Ce logiciel est un programme informatique servant à aider les développeurs  -
     * Delphi avec une bibliothèque polyvalente, adaptable et fragmentable.        -
     *                                                                             -
     * Ce logiciel est régi par la licence CeCILL-C soumise au droit français et   -
     * respectant les principes de diffusion des logiciels libres. Vous pouvez     -
     * utiliser, modifier et/ou redistribuer ce programme sous les conditions      -
     * de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA    -
     * sur le site "http://www.cecill.info".                                       -
     *                                                                             -
     * En contrepartie de l'accessibilité au code source et des droits de copie,   -
     * de modification et de redistribution accordés par cette licence, il n'est   -
     * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,   -
     * seule une responsabilité restreinte pèse sur l'auteur du programme,  le     -
     * titulaire des droits patrimoniaux et les concédants successifs.             -
     *                                                                             -
     * A cet égard  l'attention de l'utilisateur est attirée sur les risques       -
     * associés au chargement,  à l'utilisation,  à la modification et/ou au       -
     * développement et à la reproduction du logiciel par l'utilisateur étant      -
     * donné sa spécificité de logiciel libre, qui peut le rendre complexe à       -
     * manipuler et qui le réserve donc à des développeurs et des professionnels   -
     * avertis possédant  des  connaissances  informatiques approfondies.  Les     -
     * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du      -
     * logiciel à leurs besoins dans des conditions permettant d'assurer la        -
     * sécurité de leurs systèmes et ou de leurs données et, plus généralement,    -
     * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.          -
     *                                                                             -
     * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez      -
     * pris connaissance de la licence CeCILL-C, et que vous en avez accepté les   -
     * termes.                                                                     -
     *                                                                             -
     *----------------------------------------------------------------------------*)
    unit SLT.Common.TCP;
     
    interface
     
    {*$DEFINE DEBUG_SLT_TCP*}
     
    {$IFDEF MSWINDOWS}
    uses System.SysUtils, System.Classes, System.Win.ScktComp, System.SyncObjs,
      Winapi.Windows, Winapi.WinSock;
    {$ELSE MSWINDOWS}
    {$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTRemoteMessenger'}
    {$ENDIF MSWINDOWS}
     
    type
      { Forward class declarations }
      TSLTRemoteMessenger = class;
      TSLTRemoteMessengerServerClientThread = class;
      TSLTRemoteMessengerClientThread = class;
      TSLTRemoteMessengerQueueThread = class;
     
      { Types declarations }
     
      TSLTRemoteMessageStarting = Byte;
      TSLTRemoteMessageEnding = Byte;
      TSLTRemoteMessageHeader = packed record
        Starting: TSLTRemoteMessageStarting;
        DataLen: Integer;
        MessageID: Cardinal;
      end;
      TSLTRemoteMessageFooter = packed record
        MessageLen: Integer;
        Ending: TSLTRemoteMessageEnding;
      end;
      TSLTRemoteMessageState = (rmsOK, rmsInvalid);
      TSLTRemoteMessageSocketHandle = Winapi.WinSock.TSocket;
      PSLTRemoteMessage = ^TSLTRemoteMessage;
      TSLTRemoteMessage = record
        Header: TSLTRemoteMessageHeader;
        Origin: TSLTRemoteMessageSocketHandle;
        State: TSLTRemoteMessageState;
        Data: Pointer;
        Footer: TSLTRemoteMessageFooter;
      end;
     
      TSLTRemoteMessengerReadEvent = procedure(Sender: TObject; AOrigin: TSLTRemoteMessageSocketHandle; AMessageState: TSLTRemoteMessageState; AData: Pointer; ADataLen: Integer) of object;
      TSLTRemoteMessengerIdleEvent = procedure(Sender: TObject; AIdleSocket: TSLTRemoteMessageSocketHandle) of object;
      TSLTRemoteMessengerDisconnectEvent = procedure(Sender: TObject; ASocket: TSLTRemoteMessageSocketHandle) of object;
     
      TSLTRemoteMessengerClientInfo = record
        HostHandle: TSLTRemoteMessageSocketHandle;
        HostName: string;
        HostIPAddressV4: string;
      end;
     
      { Class declarations }
      /// <summary>ESLTRemoteMessengerError est l'erreur spécifique émise par le TSLTRemoteMessenger</summary>
      /// <remarks>La classe TSLTRemoteMessenger peut émettre d'autres types d'exception RTL ou VCL</remarks>
      ESLTRemoteMessengerError = class(Exception);
     
      /// <summary>TSLTRemoteMessenger gère un échange de données inter-processus via TCP/IP</summary>
      TSLTRemoteMessenger = class(TObject)
      private
        const
          START_OF_MESSAGE: TSLTRemoteMessageStarting = $FD; // ý
          END_OF_MESSAGE: TSLTRemoteMessageEnding = $FE; // þ
      strict private
        // Membres Privés
        FServer: TServerSocket;
        FServerReaders: TThreadList;
        FClient: TClientSocket;
        FClientReader: TSLTRemoteMessengerClientThread;
        FIsClient: Boolean;
        FIsServer: Boolean;
        FHost: string;
        FPort: Word;
        FMessageQueue: TSLTRemoteMessengerQueueThread;
        FOnMessage: TSLTRemoteMessengerReadEvent;
        FMessageID: Cardinal;
        FOnIdle: TSLTRemoteMessengerIdleEvent;
        FOnDisconnect: TSLTRemoteMessengerDisconnectEvent;
     
        // Méthodes Privées
        procedure ThreadFactory(Sender: TObject; ClientSocket: TServerClientWinSocket; var SocketThread: TServerClientThread);
        procedure ClientErrorEventHandler(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
        procedure ClientDisconnectEventHandler(Sender: TObject; Socket: TCustomWinSocket);
        procedure DoDisconnect(Socket: TCustomWinSocket);
        function BuildMessage(AData: Pointer; ADataLen: Integer): TSLTRemoteMessage;
        function SendData(ASocket: TCustomWinSocket; AMessage: TSLTRemoteMessage): Boolean;
        procedure TerminateServerClientThread(ASocket: TCustomWinSocket);
     
        // Accesseurs
        function GetClientCount(): Integer;
        function GetClients(Index: Integer): TSLTRemoteMessengerClientInfo;
     
        // Méthodes Privées statiques
        class function IndexOfSocketHandle(AServerSocket: TServerSocket; AClientSocketHandle: TSLTRemoteMessageSocketHandle): Integer;
      private
        // Méthodes Privées utilisables par les classes amies
        procedure AddMessage(AMessage: PSLTRemoteMessage);
        procedure NotifyMessage(AMessage: TSLTRemoteMessage);
        procedure RemoveServerReader(AThread: TServerClientThread);
        procedure Idle(AIdleSocket: TSLTRemoteMessageSocketHandle);
      public
        // Constructeurs Publiques
        destructor Destroy(); override;
     
        // Méthodes Publiques
        function Listen(): Boolean;
        function Connect(): Boolean;
        procedure Close();
        function SendDataToServer(AData: Pointer; ADataLen: Integer): Boolean;
        function SendDataToClient(ADestination: TSLTRemoteMessageSocketHandle; AData: Pointer; ADataLen: Integer): Boolean;
        function SendDataToAllClient(AData: Pointer; ADataLen: Integer): Boolean;
     
        // Propriétés Publiques
        property Host: string read FHost write FHost;
        property Port: Word read FPort write FPort;
        property IsClient: Boolean read FIsClient;
        property IsServer: Boolean read FIsServer;
        property ClientCount: Integer read GetClientCount;
        property Clients[Index: Integer]: TSLTRemoteMessengerClientInfo read GetClients;
        property OnMessage: TSLTRemoteMessengerReadEvent read FOnMessage write FOnMessage;
        property OnIdle: TSLTRemoteMessengerIdleEvent read FOnIdle write FOnIdle;
        property OnDisconnect: TSLTRemoteMessengerDisconnectEvent read FOnDisconnect write FOnDisconnect;
      end;
     
      TSLTRemoteMessengerServerClientThread = class(TServerClientThread)
      private
        const
          KEEP_ALIVE_TIME_OUT = 60000; // 60 secondes !
      private
        // Membres Privés
        FMessenger: TSLTRemoteMessenger;
      protected
        // Méthodes redéfinies
        procedure Execute(); override;
      public
        // Constructeurs Publiques
        constructor Create(AMessenger: TSLTRemoteMessenger; ASocket: TServerClientWinSocket);
        destructor Destroy(); override;
      end;
     
      TSLTRemoteMessengerClientThread = class(TThread)
      private
        const
          READ_DELAY = 60000; // 60 secondes !
      private
        // Membres Privés
        FMessenger: TSLTRemoteMessenger;
        FSocket: TClientWinSocket;
      protected
        // Méthodes redéfinies
        procedure Execute(); override;
      public
        // Constructeurs Publiques
        constructor Create(AMessenger: TSLTRemoteMessenger; ASocket: TClientWinSocket);
      end;
     
      TSLTRemoteMessengerClientReader = class(TWinSocketStream)
      private
        const
          BUFFER_LEN = 1024;
          READ_TIME_OUT = BUFFER_LEN * 8; // ce qui donne un débit mini de 1 bit/ms = 1 Kbits/s pour un réseau qui devrait être assuré avec un réseau à 1 Gbits/s !!!
      private
        // Membres Privés
        FMessenger: TSLTRemoteMessenger;
        FSocket: TCustomWinSocket;
        FWaitDelay: Longint;
        FBuffer: array[0..BUFFER_LEN-1] of Byte;
        FRemainingBuffer: record
          Data: Pointer;
          DataLen: Integer;
        end;
        // Méthodes Privées
        procedure DoIdle();
        procedure ScanBuffer(AOrigin: TSLTRemoteMessageSocketHandle; AData: PByte; ADataLen: Integer);
        procedure AddMessage(AOrigin: TSLTRemoteMessageSocketHandle; AData: PByte; ADataLen: Integer);
        procedure UnPackMessage(AOrigin: TSLTRemoteMessageSocketHandle; AData: PByte; out AMessage: TSLTRemoteMessage);
      protected
        // Méthodes redéfinies
        procedure Process(); 
      public
        // Constructeurs Publiques
        constructor Create(AMessenger: TSLTRemoteMessenger; ASocket: TCustomWinSocket; AWaitDelay: Longint);
        destructor Destroy(); override;
      end;
     
     
      TSLTRemoteMessengerQueueThread = class(TThread)
      strict private
        // Membres Privés
        FMessenger: TSLTRemoteMessenger;
        FMessageList: TThreadList;
        FSignal: TEvent;
        // Méthodes Privées
        procedure ClearMessageList();
        procedure Notify();
      private
        // Méthodes Privées utilisables par les classes amies
        procedure AddMessage(AMessage: PSLTRemoteMessage);
      protected
        // Méthodes redéfinies
        procedure Execute(); override;
        procedure TerminatedSet(); override;
      public
        // Constructeurs Publiques
        constructor Create(AMessenger: TSLTRemoteMessenger);
        destructor Destroy(); override;
     
      end;
     
     
    implementation
     
    {$IFDEF DEBUG_SLT_TCP}
    uses
      SLT.Common.Tracing;
    {$ENDIF DEBUG_SLT_TCP}
     
    {$IFDEF DEBUG_SLT_TCP}
    procedure OutputDebugTCP(const Msg: string);
    begin
      TSLTDebugLogger.OutputDebugString('[SLT.TCP]', Format('Thread : %0:d - %1:s', [GetCurrentThreadID(), Msg]));
    end;
    {$ENDIF DEBUG_SLT_TCP}
     
    { TSLTRemoteMessenger }
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.AddMessage(AMessage: PSLTRemoteMessage);
    begin
      FMessageQueue.AddMessage(AMessage);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.BuildMessage(AData: Pointer; ADataLen: Integer): TSLTRemoteMessage;
    begin
      Inc(FMessageID);
     
      Result.Header.Starting := START_OF_MESSAGE;
      Result.Header.DataLen := ADataLen;
      Result.Header.MessageID := FMessageID;
      Result.Origin := 0;
      Result.Data := AData;
      Result.Footer.MessageLen := SizeOf(TSLTRemoteMessageHeader) + Result.Header.DataLen + SizeOf(TSLTRemoteMessageFooter);  
      Result.Footer.Ending := END_OF_MESSAGE;
      Result.State := rmsOK;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.ClientDisconnectEventHandler(Sender: TObject; Socket: TCustomWinSocket);
    begin
      if Assigned(FServer) and (Sender = FServer.Socket) then
      begin
        TerminateServerClientThread(Socket);
        DoDisconnect(Socket);
      end;
     
      if Sender = FClient then
      begin
        DoDisconnect(Socket);
        FIsClient := False;
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.ClientErrorEventHandler(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    begin
      {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('Code d''Erreur = ' +  IntToStr(ErrorCode));{$ENDIF DEBUG_SLT_TCP}
      ErrorCode := 0;
      try
        Socket.Close();
      except
        on E: Exception do
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('Exception durant la fermeture d''un socket en erreur : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.Close();
    begin
      FIsClient := False;
      FIsServer := False;
     
      if Assigned(FMessageQueue) then
        FMessageQueue.Terminate();
     
      if Assigned(FClientReader) then
        FClientReader.Terminate();
     
      if Assigned(FServerReaders) then
        FServerReaders.Clear();
     
      if Assigned(FServer) then
        FServer.Close();
     
      if Assigned(FClient) then
        FClient.Close();
     
      if Assigned(FClientReader) then
        FreeAndNil(FClientReader);
     
      if Assigned(FMessageQueue) then
        FreeAndNil(FMessageQueue);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.Connect(): Boolean;
    begin
      Close();
     
      if not Assigned(FClient) then
      begin
        FClient := TClientSocket.Create(nil);
        FClient.ClientType := ctBlocking;
        FClient.OnError := ClientErrorEventHandler;
        FClient.OnDisconnect := ClientDisconnectEventHandler;
      end;
     
      if not Assigned(FMessageQueue) then
        FMessageQueue := TSLTRemoteMessengerQueueThread.Create(Self);
     
      FClient.Host := FHost;
      FClient.Port := FPort;
      try
        FClient.Open();
        Result := FClient.Active;
        FIsClient := Result;
        if Result then
          FClientReader := TSLTRemoteMessengerClientThread.Create(Self, FClient.Socket);
      except
        Result := False;
      end;
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTRemoteMessenger.Destroy();
    begin
      Close();
     
      FreeAndNil(FClient);
      FreeAndNil(FServerReaders);
      FreeAndNil(FServer);
     
      inherited Destroy();
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.DoDisconnect(Socket: TCustomWinSocket);
    begin
      try
        if Assigned(FOnDisconnect) then
          FOnDisconnect(Self, Socket.SocketHandle);
      except
        on E: Exception do
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('Exception durant la notification de déconnexion d''un socket : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.GetClientCount(): Integer;
    begin
      if Assigned(FServer) and FIsServer then
        Result := FServer.Socket.ActiveConnections
      else
        Result := 0;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.GetClients(Index: Integer): TSLTRemoteMessengerClientInfo;
    begin
      if Assigned(FServer) and FIsServer then
      begin
        with FServer.Socket.Connections[Index] do
        begin
          Result.HostHandle := SocketHandle;
          Result.HostName := RemoteHost;
          Result.HostIPAddressV4 := RemoteAddress;
        end;
      end
      else
        raise ESLTRemoteMessengerError.Create('Messenger is not Server');
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.Idle(AIdleSocket: TSLTRemoteMessageSocketHandle);
    begin
      try
        if Assigned(FOnIdle) then
          FOnIdle(Self, AIdleSocket);
      except
        on E: Exception do
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('Exception durant la gestion d''un socket inoccupé : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTRemoteMessenger.IndexOfSocketHandle(AServerSocket: TServerSocket; AClientSocketHandle: TSLTRemoteMessageSocketHandle): Integer;
    begin
      with AServerSocket.Socket do
        for Result := 0 to ActiveConnections - 1 do
          if AClientSocketHandle = Connections[Result].SocketHandle then
            Exit;
     
      Result := -1 ;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.Listen(): Boolean;
    begin
      Close();
     
      if not Assigned(FServer) then
      begin
        FServer := TServerSocket.Create(nil);
        FServer.ServerType := stThreadBlocking;
        FServer.OnClientError := ClientErrorEventHandler;
        FServer.OnGetThread := ThreadFactory;
        FServer.OnClientDisconnect := ClientDisconnectEventHandler;
      end;
     
      if not Assigned(FMessageQueue) then
        FMessageQueue := TSLTRemoteMessengerQueueThread.Create(Self);
     
      if not Assigned(FServerReaders) then
        FServerReaders := TThreadList.Create();
     
      FServer.Port := FPort;
      try
        FServer.Open();
        Result := FServer.Active;
        FIsServer := Result;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('Listen : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          Result := False;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.NotifyMessage(AMessage: TSLTRemoteMessage);
    begin
      try
        if Assigned(FOnMessage) then
          FOnMessage(Self, AMessage.Origin, AMessage.State, AMessage.Data, AMessage.Header.DataLen);
      except
        on E: Exception do
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('NotifyMessage : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.RemoveServerReader(AThread: TServerClientThread);
    var
      TmpList: TList;
      I: Integer;
      ItemPtr: Pointer;
    begin
      if Assigned(FServerReaders) then
      begin
        TmpList := FServerReaders.LockList();
        try
          for I := TmpList.Count - 1 downto 0 do
          begin
            ItemPtr := TmpList.Items[I];
            if ItemPtr = AThread then
            begin
              TmpList.Delete(I);
              Break;
            end;
          end
        finally
          FServerReaders.UnlockList();
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.SendData(ASocket: TCustomWinSocket; AMessage: TSLTRemoteMessage): Boolean;
    var
      Stream: TMemoryStream;
    begin
      // Le flux transmis comme paramètre à SendStream devient la "propriété" de l'objet socket Windows.
      // L'objet socket Windows libère le flux quand il n'en n'a plus besoin. N'essayez pas de libérer le flux une fois qu'il a été transmis comme paramètre
      Stream := TMemoryStream.Create();
      Stream.Write(AMessage.Header, SizeOf(AMessage.Header));
      Stream.Write(PByte(AMessage.Data)^, AMessage.Header.DataLen);
      Stream.Write(AMessage.Footer, SizeOf(AMessage.Footer));
      if Stream.Size = AMessage.Footer.MessageLen then
      begin
        Stream.Seek(0, soBeginning);
        Result := ASocket.SendStream(Stream);
      end
      else
      begin
        Stream.Free();
        Result := False;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.SendDataToAllClient(AData: Pointer; ADataLen: Integer): Boolean;
    var
      DataEnveloppe: TSLTRemoteMessage;
      idx, SendCount: Integer;
    begin
      Result := False;
      try
        SendCount := 0;
        if Assigned(FServer) then
        begin
          DataEnveloppe := BuildMessage(AData, ADataLen);
          DataEnveloppe.Origin := FServer.Socket.SocketHandle;
          for idx := 0 to FServer.Socket.ActiveConnections - 1 do
            if SendData(FServer.Socket.Connections[idx], DataEnveloppe) then
              Inc(SendCount);
     
          Result := SendCount > 0;
        end;
      except
        on E: ESocketError do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('SendDataToAllClient : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          Result := False;
        end;
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('SendDataToAllClient : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          raise;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.SendDataToClient(ADestination: TSLTRemoteMessageSocketHandle; AData: Pointer; ADataLen: Integer): Boolean;
    var
      DataEnveloppe: TSLTRemoteMessage;
      idx: Integer;
    begin
      Result := False;
      try
        if Assigned(FServer) then
        begin
          DataEnveloppe := BuildMessage(AData, ADataLen);
          DataEnveloppe.Origin := FServer.Socket.SocketHandle;
          // Pour les sockets bloquants, SendBuf renvoie le nombre d'octets actuellement écrits
          idx := IndexOfSocketHandle(FServer, ADestination);
          if idx >= 0 then
            Result := SendData(FServer.Socket.Connections[idx], DataEnveloppe);
        end;
      except
        on E: ESocketError do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('SendDataToClient : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          Result := False;
        end;
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('SendDataToClient : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          raise;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTRemoteMessenger.SendDataToServer(AData: Pointer; ADataLen: Integer): Boolean;
    var
      DataEnveloppe: TSLTRemoteMessage;
    begin
      Result := False;
      try
        if Assigned(FClient) then
        begin
          DataEnveloppe := BuildMessage(AData, ADataLen);
          DataEnveloppe.Origin := FClient.Socket.SocketHandle;
          // Si WinSock peut accepter les données supplémentaires, SendBuf renvoie immédiatement le nombre d'octets mis en file d'attente
          // Si l'espace du tampon interne WinSock ne peut pas accepter le tampon envoyé, SendBuf renvoie -1 et aucune donnée n'est mise en file d'attente
          // Dans ce cas, attendez un peu, pour que WinSock ait la possibilité d'émettre les données déjà mises en file d'attente, puis réessayez.
          Result := SendData(FClient.Socket, DataEnveloppe);
        end;
      except
        on E: ESocketError do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('SendDataToServer : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          Result := False;
        end;
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('SendDataToServer : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          raise;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.TerminateServerClientThread(ASocket: TCustomWinSocket);
    var
      TmpList: TList;
      I: Integer;
      ItemPtr: TSLTRemoteMessengerServerClientThread;
    begin
      if Assigned(FServerReaders) then
      begin
        TmpList := FServerReaders.LockList();
        try
          for I := TmpList.Count - 1 downto 0 do
          begin
            ItemPtr := TSLTRemoteMessengerServerClientThread(TmpList.Items[I]);
            if ItemPtr.ClientSocket = ASocket then
              ItemPtr.Terminate();
          end
        finally
          FServerReaders.UnlockList();
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessenger.ThreadFactory(Sender: TObject; ClientSocket: TServerClientWinSocket; var SocketThread: TServerClientThread);
    begin
      SocketThread := TSLTRemoteMessengerServerClientThread.Create(Self, ClientSocket);
      FServerReaders.Add(SocketThread);
    end;
     
    { TSLTRemoteMessengerServerClientThread }
     
    //------------------------------------------------------------------------------
    constructor TSLTRemoteMessengerServerClientThread.Create(AMessenger: TSLTRemoteMessenger; ASocket: TServerClientWinSocket);
    begin
      inherited Create(False, ASocket);
     
      // Libération gérer par le Server
      FMessenger := AMessenger;
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTRemoteMessengerServerClientThread.Destroy();
    begin
      FMessenger.RemoveServerReader(Self);
     
      inherited Destroy();
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerServerClientThread.Execute();
    var
      Stream: TSLTRemoteMessengerClientReader;
    begin
      try
        Stream := TSLTRemoteMessengerClientReader.Create(FMessenger, ClientSocket, KEEP_ALIVE_TIME_OUT);
        try
          while not Terminated and ClientSocket.Connected do
            Stream.Process();
        finally
          Stream.Free();
        end;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('ServerClientThread : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          ClientSocket.Close();
        end;
      end;
    end; 
     
    { TSLTRemoteMessengerClientThread }
     
    //------------------------------------------------------------------------------
    constructor TSLTRemoteMessengerClientThread.Create(AMessenger: TSLTRemoteMessenger; ASocket: TClientWinSocket);
    begin
      inherited Create(False);
     
      FMessenger := AMessenger;
      FSocket := ASocket;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerClientThread.Execute();
    var
      Stream: TSLTRemoteMessengerClientReader;
    begin
      try
        Stream := TSLTRemoteMessengerClientReader.Create(FMessenger, FSocket, READ_DELAY);
        try
          while not Terminated and FSocket.Connected do
            Stream.Process();
        finally
          Stream.Free();
        end;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('ClientThread : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          FSocket.Close();
        end;
      end;
    end; 
     
    { TSLTRemoteMessengerClientReader } 
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerClientReader.AddMessage(AOrigin: TSLTRemoteMessageSocketHandle; AData: PByte; ADataLen: Integer);
    var
      CurrentMessage: PSLTRemoteMessage;
    begin
      // Création d'un nouveau pointeur CurrentMessage sur un TSLTRemoteMessage
      New(CurrentMessage);
      // Décomposition du MessageBuffer dans CurrentMessage
      UnPackMessage(AOrigin, AData, CurrentMessage^);
      // C'est une TThreadList donc la gestion de Section Critique est incluse dans le Add()
      FMessenger.AddMessage(CurrentMessage);
    end;
     
    //------------------------------------------------------------------------------
    constructor TSLTRemoteMessengerClientReader.Create(AMessenger: TSLTRemoteMessenger; ASocket: TCustomWinSocket; AWaitDelay: Longint);
    begin
      inherited Create(ASocket, READ_TIME_OUT);
     
      FSocket := ASocket;
      FMessenger := AMessenger;
      FWaitDelay := AWaitDelay;
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTRemoteMessengerClientReader.Destroy();
    begin
      if Assigned(FRemainingBuffer.Data) then
      begin
        FreeMem(FRemainingBuffer.Data);
        FRemainingBuffer.Data := nil;
        FRemainingBuffer.DataLen := 0;
      end;
     
      inherited Destroy();
    end;      
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerClientReader.DoIdle();
    begin
      (* Pour un TServerSocket, je pourrais utiliser le KeepAlive du TCP/IP : RFC 1122
         Il faut pour cela utiliser l'API setsockopt \ SO_KEEPALIVE pour activer le KeepAlive pour le Handle du socket
         Ainsi que l'API WSAIoctl \ SIO_KEEPALIVE_VALS pour changer les délais
         Je pense plutôt mettre en place un Keep Alive manuel géré par l'utilisateur du Messenger *)
      FMessenger.Idle(FSocket.SocketHandle);
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerClientReader.Process();
    var
      ReadCount: Integer;
    begin
      // WaitForData return on
      // Data is available for reading
      // Connection has been closed/reset/terminated.
      if WaitForData(FWaitDelay) then
      begin
        if FSocket.Connected and (FSocket.SocketHandle > 0) then
          ReadCount := Read(FBuffer[0], BUFFER_LEN)
        else
          ReadCount := 0;
     
        if ReadCount > 0 then
          ScanBuffer(FSocket.SocketHandle, @FBuffer[0], ReadCount)
        else
          FSocket.Close(); // Connexion trop lente ou déconnectée !
      end
      else
        if FSocket.Connected then
          DoIdle();
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerClientReader.ScanBuffer(AOrigin: TSLTRemoteMessageSocketHandle; AData: PByte; ADataLen: Integer);
     
      procedure AddBuffer(ANewBuffer: PByte; ANewBufferLen: Integer);
      var
        P: PByte;
      begin
        // Cumul du nouveau buffer avec le relicat
        // le relicat est vide, on copie simplement
        // le relicat n'est pas vide, on agrandie et l'on ajoute les nouvelles données
        if not Assigned(FRemainingBuffer.Data) then
        begin
          GetMem(FRemainingBuffer.Data, ANewBufferLen);
          P := FRemainingBuffer.Data;
          FRemainingBuffer.DataLen := ANewBufferLen;
          CopyMemory(P, ANewBuffer, ANewBufferLen);
        end
        else
        begin
          ReallocMem(FRemainingBuffer.Data, FRemainingBuffer.DataLen + ANewBufferLen);
          P := FRemainingBuffer.Data;
          Inc(P, FRemainingBuffer.DataLen);
          Inc(FRemainingBuffer.DataLen, ANewBufferLen);
          CopyMemory(P, ANewBuffer, ANewBufferLen);
        end;
      end;
     
      function SearchByte(AData: PByte; ADataLen: Integer; AByte: Byte): Integer;
      var
        P: PByte;
      begin
        P := FRemainingBuffer.Data;
        for Result := 0 to FRemainingBuffer.DataLen-1 do
        begin
          if P^ = AByte then
            Exit;
     
          Inc(P);
        end;
        Result := -1;
      end;
     
    var
      iSOM, iEOM, iEOL : Integer;
      lEOM: Integer;
      TempRMH : TSLTRemoteMessageHeader;
      P: PByte; // Le compilateur autorise l'utilisation d'un PByte ou PChar comme un tableau !
      ScannedBuffer: Pointer;
      ScannedBufferLen: Integer;
    begin
      try
        AddBuffer(AData, ADataLen);
        // La donnée analysable par SOM et EOM doit forcément être assez grande pour contenir Header et Footer !
        if FRemainingBuffer.DataLen >= SizeOf(TSLTRemoteMessageHeader)+SizeOf(TSLTRemoteMessageFooter) then
        begin
          repeat
            // si une seule position est à zéro, c'est que le buffer n'est pas complet
     
            // Recherche du SOM (START_OF_MESSAGE : $FD = 253) dans FRemainingBuffer.Data
            iSOM := SearchByte(FRemainingBuffer.Data, FRemainingBuffer.DataLen, TSLTRemoteMessenger.START_OF_MESSAGE);
     
            // il est possible d'avoir des EOM þ imprévus, il faut donc plutôt géré l'entête
            // Protection pour gérer les þ imprévus
            // Lecture dans le champ DataLen du nombre d'octets des donnees
            if iSOM >= 0 then
            begin
              P := FRemainingBuffer.Data;
              lEOM := SizeOf(TSLTRemoteMessageEnding);
              iEOL := FRemainingBuffer.DataLen;
              // @P[iSOM] car la position du SOM est la première incluse dans le BufferRestant
              CopyMemory(@TempRMH, @P[iSOM], SizeOf(TempRMH));
              // SizeOf(TSLTRemoteMessageFooter) - lEOM car la position du EOM est la dernière incluse dans le TSLTRemoteMessageFooter
              iEOM := iSOM + SizeOf(TempRMH) + TempRMH.DataLen + SizeOf(TSLTRemoteMessageFooter) - lEOM;
              // Controle dans la location iEOM si il est ègal a EOM (FD 254)
              if (iEOL > iEOM) and (P[iEOM] = TSLTRemoteMessenger.END_OF_MESSAGE) then
              begin
                // le message est correct car il y a bien le þ comme prévu !
                // On peut considerer valide le message contenu de l'octet iSOM à l'octet iEOM,
                // Ce mécanisme gère les éventuel FD ou FE compris en tant que donnees et non pas en SOM ou EOM
                iEOL := FRemainingBuffer.DataLen;
     
                // Comme le message a des bornes correctes, on décompose celui-ci
                // iEOM - iSOM + lEOM car SOM et EOM sont inclus dans le Message
                ScannedBufferLen := iEOM - iSOM + lEOM;
                GetMem(ScannedBuffer, ScannedBufferLen);
                try
                  CopyMemory(ScannedBuffer, FRemainingBuffer.Data, ScannedBufferLen);
                  AddMessage(AOrigin, ScannedBuffer, ScannedBufferLen);
                finally
                  FreeMem(ScannedBuffer);
                end;
     
                // Récupération de la fin du buffer pour obtenir les messages suivants
                if iEOL - ScannedBufferLen > 0 then
                begin
                  CopyMemory(FRemainingBuffer.Data, @P[ScannedBufferLen], iEOL - ScannedBufferLen);
                  FRemainingBuffer.DataLen := iEOL - ScannedBufferLen;
                end
                else
                begin
                  FreeMem(FRemainingBuffer.Data);
                  FRemainingBuffer.Data := nil;
                  FRemainingBuffer.DataLen := 0;
                  Break;
                end;
              end
              else
                Break; // Force la sortie pour obtenir plus de buffer !
            end;
     
          // Fin de la boucle si il n'y a plus délimiteur de début de message
          until iSOM < 0;
        end;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('ScanBuffer : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          raise;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerClientReader.UnPackMessage(AOrigin: TSLTRemoteMessageSocketHandle; AData: PByte; out AMessage: TSLTRemoteMessage);
    var
      ComputedMessageLen: Integer;
    begin
      AMessage.State := rmsInvalid;
      try
        AMessage.Data := nil;
     
        // Récupération de l'Enveloppe du Message
        CopyMemory(@AMessage.Header, AData, SizeOf(AMessage.Header));
     
        // Décalage du pointeur pour parcourir le AData
        Inc(AData, SizeOf(AMessage.Header));
     
        // On mémorise l'expediteur
        AMessage.Origin := AOrigin;
     
        // Récupération du corps du Message (grace au header issu de AData, on connait la taille de la donnée interne AMessage.Data)
        GetMem(AMessage.Data, AMessage.Header.DataLen);
        CopyMemory(AMessage.Data, AData, AMessage.Header.DataLen);
     
        // Décalage du pointeur pour parcourir le AData
        Inc(AData, AMessage.Header.DataLen);
     
        // Récupération de la fin du Message
        CopyMemory(@AMessage.Footer, AData, SizeOf(AMessage.Footer));
     
        ComputedMessageLen := SizeOf(TSLTRemoteMessageHeader) + AMessage.Header.DataLen + SizeOf(TSLTRemoteMessageFooter);
     
        if (AMessage.Header.Starting = TSLTRemoteMessenger.START_OF_MESSAGE) and (AMessage.Footer.Ending = TSLTRemoteMessenger.END_OF_MESSAGE)
          and (AMessage.Footer.MessageLen = ComputedMessageLen) then
          AMessage.State := rmsOK;
      except
        on E: Exception do
        begin
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('UnPackMessage : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
          if Assigned(AMessage.Data) then
            FreeAndNil(AMessage.Data);
        end;
      end;
    end;
     
    { TSLTRemoteMessengerQueueThread }
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerQueueThread.AddMessage(AMessage: PSLTRemoteMessage);
    begin
      if not Terminated and Assigned(FMessageList) and Assigned(FSignal) then
      begin
        FMessageList.Add(AMessage);
        FSignal.SetEvent();
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerQueueThread.ClearMessageList();
    var
      TmpList: TList;
      I: Integer;
      ItemPtr: PSLTRemoteMessage;
    begin
      if Assigned(FMessageList) then
      begin
        TmpList := FMessageList.LockList();
        try
          for I := TmpList.Count - 1 downto 0 do
          begin
            ItemPtr := PSLTRemoteMessage(TmpList.Items[I]);
            TmpList.Delete(I);
            Dispose(ItemPtr);
          end
        finally
          FMessageList.UnlockList();
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    constructor TSLTRemoteMessengerQueueThread.Create(AMessenger: TSLTRemoteMessenger);
    begin
      inherited Create(False);
     
      FMessenger := AMessenger;
      FSignal := TEvent.Create(nil, False, False, '', False); // Reset Auto !
      FMessageList := TThreadList.Create();
    end;
     
    //------------------------------------------------------------------------------
    destructor TSLTRemoteMessengerQueueThread.Destroy();
    begin
      if not Terminated then
        Terminate();
     
      if not Finished and not Suspended then
        WaitFor(); // On attend qu'il finisse son traitement déjà en cours
     
      ClearMessageList();
     
      // TThreadList.Destroy is thread safe !
      FreeAndNil(FMessageList);
      FreeAndNil(FSignal);
     
      inherited Destroy();
    end;   
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerQueueThread.Execute();
    var
      wr: TWaitResult;
    begin
      while not Terminated do
      begin
        wr := FSignal.WaitFor(INFINITE);
        case wr of
          wrSignaled:
            begin
              if not Terminated then
                Notify();
            end;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerQueueThread.Notify();
    var
      MoreItem, HaveItem: Boolean;
      Item: TSLTRemoteMessage;
      ItemPtr: PSLTRemoteMessage;
      TmpList: TList;
    begin
      try
        if not Terminated then
        begin
          MoreItem := False;
     
          // Parcours de la liste
          repeat
            HaveItem := False;
     
            Item.Data := nil;
            try
              // Phase 1 - Récupération d'un Elément (on bloque la liste juste le temps qu'il faut)
              TmpList := FMessageList.LockList();
              try
                if TmpList.Count > 0 then
                begin
                  ItemPtr := PSLTRemoteMessage(TmpList.First());
                  Item := ItemPtr^; // Copie mais Item.Data c'est toujours un pointeur !
                  TmpList.Delete(0);
                  Dispose(ItemPtr);
     
                  HaveItem := True;
                  MoreItem := TmpList.Count > 0;
                end
              finally
                FMessageList.UnlockList();
              end;
     
              // Phase 2 - Traitement de l'Element !
              if HaveItem then
                FMessenger.NotifyMessage(Item);
            finally
              if Assigned(Item.Data) then
              begin
                FreeMem(Item.Data);
                Item.Data := nil;
              end;
            end;
     
          until not MoreItem or Terminated;
        end
      except
        on E: Exception do
          {$IFDEF DEBUG_SLT_TCP}OutputDebugTCP('Notify Queue : ' + E.Message);{$ENDIF DEBUG_SLT_TCP}
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSLTRemoteMessengerQueueThread.TerminatedSet();
    begin
      inherited TerminatedSet();
     
      if Assigned(FSignal) then
        FSignal.SetEvent(); // Arrêt prématuré !
    end;
     
     
     
     
    end.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    322
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Janvier 2009
    Messages : 322
    Points : 310
    Points
    310
    Par défaut
    Merci Shai

    C'est super

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. ouvrir un fichier qui n'est pas dans le répertoire de travail
    Par El_bennito dans le forum Interfaces Graphiques
    Réponses: 2
    Dernier message: 25/06/2009, 16h38
  2. [VB6] Comment faire pour lire un fichier en streaming ?
    Par MegaBigBoss dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 20/04/2006, 17h56
  3. Réponses: 6
    Dernier message: 08/04/2005, 03h00
  4. [TP]comment faire pour lire un fichier son
    Par sovo dans le forum Turbo Pascal
    Réponses: 1
    Dernier message: 19/09/2004, 19h33
  5. Probleme pour lire un fichier Ini
    Par Sebinou dans le forum C++Builder
    Réponses: 11
    Dernier message: 10/03/2004, 23h22

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo