Sie sind auf Seite 1von 2

1

procedure TMainForm.CreateTCPIPConnection;

2

begin

3

if not Assigned(ZPReadThread) then

4

begin

5

IdTCPClient.Host := AddressEdit.Text;

6

IdTCPClient.Port := StrToIntDef(PortEdit.Text, 4769);

7

try

8

ZPReadThread := TReadingThread.Create(IdTCPClient);

9

try

10

ZPReadThread.OnData := DataReceived;

11

ZPReadThread.Start;

12

except

13

FreeAndNil(ZPReadThread);

14

raise;

15

end;

16

except

17

on E: Exception do

18

begin

19

{$IFDEF TRACEDEBUG}AddDebugEntry('TCP/IP exception creating read thread :

'+E.Message);{$ENDIF}

20

end;

21

end;

22

end;

23

end;

24

25

procedure TReadingThread.Execute;

26

begin

27

{$IFDEF TRACEDEBUG}AddDebugEntry('Read thread created');{$ENDIF}

28

29

try

30

FClient.ConnectTimeout := 10000; // <-- use whatever you want

31

FClient.Connect;

32

except

33

on E: Exception do

34

begin

35

{$IFDEF TRACEDEBUG}AddDebugEntry('TCP/IP connect exception :

'+E.Message);{$ENDIF}

36

raise;

37

end;

38

end;

39

40

try

41

while not Terminated do

42

begin

43

{$IFDEF TRACEDEBUG}AddDebugEntry('Read thread ReadLn (before)');{$ENDIF}

44

try

45

FData := FClient.IOHandler.ReadLn;

46

except

47

on E: Exception do

48

begin

49

{$IFDEF TRACEDEBUG}AddDebugEntry('TCP/IP IOHandler.ReadLn exception :

'+E.Message);{$ENDIF}

50

raise;

51

end;

52

end;

53

//FClient.IOHandler.ReadBytes(AData, sizeof(TWaveFormSample), False);

54

{$IFDEF TRACEDEBUG}AddDebugEntry('Read thread ReadLn (after)');{$ENDIF}

55

if (FData <> '') and Assigned(FOnData) then

56

Synchronize(DataReceived);

57

//Sleep(1);

58

end;

59

finally

60

FClient.Disconnect;

61

end;

62

end;

63

64

procedure TReadingThread.DoTerminate;

65

begin

66

{$IFDEF TRACEDEBUG}AddDebugEntry('Read thread terminating');{$ENDIF}

67

inherited;

68

end;

69

70

type

71

TIdStackBSDBaseAccess = class(TIdStackBSDBase)

72

end;

73

74

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);

75

begin

76

if Assigned(ZPReadThread) then

77

begin

78

{$IFDEF TRACEDEBUG}AddDebugEntry('Terminating Read thread');{$ENDIF}

79

ZPReadThread.Terminate;

80

try

81

{$IFDEF TRACEDEBUG}AddDebugEntry('Shutting down socket');{$ENDIF}

82

TIdStackBSDBaseAccess(GBSDStack).WSShutdown(IdTCPClient.Socket.Binding.Handle, Id_SD_Both);

83

finally

84

{$IFDEF TRACEDEBUG}AddDebugEntry('Waiting for read thread termination');{$ENDIF}

85

ZPReadThread.WaitFor;

86

{$IFDEF TRACEDEBUG}AddDebugEntry('Finished waiting for read thread termination');{$ENDIF}

87

FreeAndNil(ZPReadThread);

88

end;

89

end;

90

end;