unit Unit1;
interface
uses
IdCustomTCPServer, IdTCPClient, IdContext,
SysUtils, Classes, Forms, StdCtrls, Controls;
type
TClientThread =
class(TThread)
private
TCPClient: TIdTCPClient;
FLog: TStrings;
public
constructor Create(AHost:
string; APort: Word; ALog: TStrings);
destructor Destroy;
override;
procedure Execute;
override;
end;
TMyServer =
class (TIdCustomTCPServer)
protected
function DoExecute(AContext: TIdContext): Boolean;
override;
end;
TServerPushExampleForm =
class(TForm)
MemoLog: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
ExampleClient: TClientThread;
ExampleServer: TMyServer;
end;
var
ServerPushExampleForm: TServerPushExampleForm;
implementation
uses
IdGlobal;
{$R *.dfm}
procedure TServerPushExampleForm.FormCreate(Sender: TObject);
begin
MemoLog.Clear;
ExampleServer := TMyServer.Create;
ExampleServer.DefaultPort := 8088;
ExampleServer.Active := True;
ExampleClient := TClientThread.Create('
localhost', 8088, MemoLog.Lines);
end;
procedure TServerPushExampleForm.FormDestroy(Sender: TObject);
begin
ExampleServer.Free;
ExampleClient.Terminate;
ExampleClient.WaitFor;
ExampleClient.Free;
end;
{ TMyServer }
function TMyServer.DoExecute(AContext: TIdContext): Boolean;
var
Request:
string;
begin
Result :=
inherited;
Request := AContext.Connection.IOHandler.ReadLn(IndyTextEncoding_UTF8);
// simulate hard work
Sleep(Random(4000));
AContext.Connection.IOHandler.WriteLn('
reply for ' + Request,
IndyTextEncoding_UTF8);
end;
{ TClientThread }
constructor TClientThread.Create(AHost:
string; APort: Word; ALog: TStrings);
begin
inherited Create(False);
FLog := ALog;
TCPClient := TIdTCPClient.Create;
TCPClient.Host := AHost;
TCPClient.Port := APort;
TCPClient.ReadTimeout := 500;
end;
destructor TClientThread.Destroy;
begin
TCPClient.Free;
inherited;
end;
procedure TClientThread.Execute;
var
Request, Reply:
string;
RequestNr: Integer;
begin
RequestNr := 0;
TCPClient.Connect;
while not Terminated
do
begin
Inc(RequestNr);
Request := Format ('
request %d', [RequestNr]);
TThread.Queue(
nil,
procedure
begin
FLog.Append('
send: ' + Request);
end);
TCPClient.IOHandler.WriteLn(Request, IndyTextEncoding_UTF8);
Reply := TCPClient.IOHandler.ReadLn(IndyTextEncoding_UTF8);
if not TCPClient.IOHandler.ReadLnTimedout
then
begin
TThread.Queue(
nil,
procedure
begin
FLog.Append('
recv: ' + Reply);
end);
end;
Sleep(2000);
end;
TCPClient.Disconnect;
end;
end.