To listening of events from a Rest server I need a long running HTTP request.
How we do that with Delphi?
My current solution works but the stop of the request from the caller side is not solved properly. I have to stop the thread by using Thread.Terminate. This thread kill leads to unwanted memory leaks. That is why I'm looking for another solution.
The request must be interuptable by the caller also in case where no new data are received from the server. I tried als asynchronous calls with BeginExecute/BeginGet but I saw the same problem that the request can not be stopped at any time without data from the server.
Here is my code which sould work at the end on different plattforms (Win/OSX/ Android):
type
TMyRestAPI = class
private
fClient: THTTPClient;
fStream: TMemoryStream;
fReadPos: Int64;
fOnReceiveData: procedure(const data: string) of object;
procedure OnRecData(const Sender: TObject; AContentLength: Int64;
AReadCount: Int64; var Abort: Boolean);
public
procedure StartRequest(const URL: string);
procedure StopRequest;
end;
procedure TMyRestAPI.StartRequest(const URL: string);
begin
fClient := THTTPClient.Create;
fClient.HandleRedirects := true;
fClient.Accept := 'text/event-stream';
fClient.OnReceiveData := OnRecData;
fStream := TMemoryStream.Create;
fReadPos := 0;
fThread := TThread.CreateAnonymousThread(
procedure
begin
fClient.Get(URL, fStream);
end);
fThread.Start;
end;
procedure TMyRestAPI.OnRecData(const Sender: TObject; AContentLength: Int64;
AReadCount: Int64; var Abort: Boolean);
var
ss: TStringStream;
resp: string;
begin
ss := TStringStream.Create;
try
fStream.Position := readPos;
ss.CopyFrom(fStream, AReadCount - fReadPos);
fOnReceiveData(ss.DataString);
fReadPos := AReadCount;
finally
ss.Free;
end;
end;
procedure TMyRestAPI.StopRequest;
begin
fThread.Terminate;
fClient.Free;
fStream.Free;
end;