I am implementing a live chat in my deplhi project, which receives new messages by doing GET
request to the server. The server itself closes connection after 20 seconds if no new messages occur. Code discribed above is located in a separate thread (it is created on visiting chat "page") so it doesnt freezes the GUI. When i go to a non-chat page from chat, i call this code outside of thread_chat
in order to make the thread exit:
if thread_chat <> nil then
begin
thread_chat.Terminate;
thread_chat := nil;
end;
However since my server timeout is 20 seconds, thread actualy closes only when it receives a response (yea, this sounds logically, since my thread loop is while not Terminated do
). So what i am looking for is to close HTTP connection in the middle of the request.
Attemp #1
Initially i looked into TerminateThread
by calling it like
TerminateThread(thread_chat.Handle, 0)
and this works fine until i try to kill thread on second time - my app completly freezes. So i went to
Attemp #2
I created a global variable URL_HTTP: TIdHTTP
and i receive the server page content with this function:
function get_URL_Content(const Url: string): string;
var URL_stream: TStringStream;
begin
URL_HTTP := TIdHTTP.Create(nil);
URL_stream := TStringStream.Create(Result);
URL_HTTP.Get(Url, URL_stream);
if URL_HTTP <> nil then
try
URL_stream.Position := 0;
Result := URL_stream.ReadString(URL_stream.Size);
finally
FreeAndNil(URL_HTTP);
FreeAndNil(URL_stream);
end;
end;
and when i call this code outside of thread_chat
if thread_chat <> nil then
begin
URL_HTTP.Disconnect;
thread_chat.Terminate;
end;
i get EidClosedSocket
exception (after some tests while writing this post, i get EAccessViolation
error instead).
I run out of ideas. How can i close HTTP request before server response?
procedure thread_chat.Execute; //overrided
begin
while not Terminated do
if check_messages then //sends request to the server, processes response, true if new message(s) exist
show_messages;
end;