RejectedSoftware Forums

Sign up

Server Sent Events

Hello,
I am new to D and vibed.

And try to implement what I for web/microservices need. Most of the stuff I found in the documentation or the books.

One point I haven't, found is how to implement Server Sent Events and keep the connection
open.

Can somebody help / point me the way how to implement this.

Thanks,
Stefan

Re: Server Sent Events

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?

Re: Server Sent Events

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;
	}
}