Главная страница | назад





Article #22866: How to send a response early in a web application action.

Question:
How to send a response early in a web application action.

Answer:

Typically, with web applications, you set Response.Content to something in an Action and let the content be sent after the action is done. But what if you want to constantly stream out data to the client web browser? To do this, you will have to use TWebRequest.WriteString in combination with TWebResponse.SendResponse.

The trick is to not set Response.Content before calling Response.SendResponse. Setting Response.Content to a string and then calling SendResponse causes the Response to send a "Content-Length:" to the web browser client. The web browser will then expect nothing longer than the Response.Content and will close the connection early.

To keep the connection open, the first thing you should do is send Response.SendResponse. This properly fills up the Response header, but doesn't set the "Content-Length:". You can then use Request.WriteString to write individual strings directly to the web browser at any time.

Here is an example action that should give you an idea of how to do this:


// This example doesn't add the proper HTML starting 
// tags for simplicity
procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
I: Integer;
S: string;
begin
// Important that this is first!
Response.SendResponse;
S := 'About to send time stamps<br>';
// Send the content early by accessing the Request
// directly and writing to it.
Request.WriteString(S);
// Send some Responses and pause to simulate lengthy operations
for I := 1 to 3 do
begin
// Pause for about 3 secs
Sleep(3000);
// Set another response
S := TimeToStr(Now) + '<br>';
Request.WriteString(S);
end;
end;

Last Modified: 24-AUG-00