Posted Tue, 3 Dec 2024 18:35:08 +0100 in reply to
Dāvis
Reply
Am 18.11.2024 um 15:50 schrieb Dāvis:
Hi!
I'm also looking into implementing server-sent events using Vibe.d but I can't find any examples/
documentation of how I would do that?
The code that I have personally written all predates widespread
server-side event browser support and uses either WebSockets or a custom
form of delayed server responses. But it should be pretty easy to
implement on the server side. Taking the PHP example on the Mozilla
page, it would look roughly like this:
void getEvents(HTTPServerRequest req, HTTPServerResponse res)
{
res.headers["X-Accel-Buffering"] = "no";
res.headers["Content-Type"] = "text/event-stream";
res.headers["Cache-Control"] = "no-cache";
auto counter = uniform(1, 10);
while (true) {
auto date = Clock.currTime(UTC()).toISOExtString();
if (--counter == 0) {
counter = uniform(1, 10);
res.bodyWriter.write(format("data: This is a message at time %s\n\n",
date);
}
res.bodyWriter.write("event: ping\n");
res.bodyWriter.write(format("data: {\"time\": \"%s\"}\n\n", date);
res.bodyWriter.flush();
sleep(1.seconds);
if (res.waitForConnectionClose(0.seconds))
break;
}
}