real-time streaming (Server-Sent Events) #422
Unanswered
jarroddavis68
asked this question in
Q&A
Replies: 2 comments
-
|
I'ved tried everything I cand find. It only seems to send once and then not again. This example works without crashing. procedure Test03();
begin
THorse.KeepConnectionAlive := True;
THorse.Get('/sse',
procedure (Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
LBuffer: TStringStream;
I: Integer;
s: string;
begin
// Set headers for SSE
Res.RawWebResponse.ContentType := 'text/event-stream';
Res.RawWebResponse.CustomHeaders.Values['Cache-Control'] := 'no-cache';
Res.RawWebResponse.CustomHeaders.Values['Connection'] := 'keep-alive';
LBuffer := TStringStream.Create('', TEncoding.UTF8);
for I := 1 to 10 do
begin
Res.RawWebResponse.ContentStream := LBuffer;
Res.RawWebResponse.FreeContentStream := False;
s := Format('id: %d' + sLineBreak + 'event: message' + sLineBreak + 'data: Event %d at %s' + sLineBreak + sLineBreak, [I, I, FormatDateTime('hh:nn:ss', Now)]);
LBuffer.WriteString(s);
writeln(LBuffer.DataString);
Res.RawWebResponse.ContentLength := LBuffer.Size;
Res.RawWebResponse.SendResponse;
LBuffer.Clear;
Sleep(1000);
end;
LBuffer.Free();
end
);
THorse.Listen(9000,
procedure
begin
WriteLn;
Write('Press ENTER to stop server...');
Readln;
THorse.StopListen;
end);
end; |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
so, I think I may have something.
procedure Test03();
var
LCtx: TidContext;
begin
THorse.Get('/sse',
procedure (Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
I: Integer;
s: string;
begin
LCtx := THorse.HTTPWebBrokerBridge.Contexts.Pull;
LCtx.Connection.IOHandler.WriteLn('HTTP/1.1 200 OK');
LCtx.Connection.IOHandler.WriteLn('Content-Type: text/event-stream; charset=UTF-8');
LCtx.Connection.IOHandler.WriteLn('Cache-Control: no-store');
LCtx.Connection.IOHandler.WriteLn('Connection: keep-alive');
LCtx.Connection.IOHandler.WriteLn('Access-Control-Allow-Origin: *');
LCtx.Connection.IOHandler.WriteLn('');
for I := 1 to 10 do
begin
s := Format('id: %d' + sLineBreak + 'event: message' + sLineBreak + 'data: Event %d at %s' + sLineBreak + sLineBreak, [I, I, FormatDateTime('hh:nn:ss', Now)]);
writeln(s);
LCtx.Connection.IOHandler.Write(s + #13#10#13#10);
LCtx.Connection.IOHandler.WriteBufferFlush;
Sleep(10);
end;
LCtx.Connection.IOHandler.WriteBufferFlush;
LCtx.Connection.Disconnect;
end
);
THorse.Listen(9000,
procedure
begin
WriteLn;
Write('Press ENTER to stop server...');
Readln;
THorse.StopListen;
end);
end;Seems to work. Hoping devs could chime in and validate this is not going to cause problems elsewhere. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible to do?
Beta Was this translation helpful? Give feedback.
All reactions