import * as mod from "https://deno.land/std@0.205.0/http/unstable_server_sent_event.ts";
Provides ServerSentEvent
and
ServerSentEventStreamTarget
which provides an interface to send
server sent events to a browser using the DOM event model.
The ServerSentEventStreamTarget
provides the .asResponse()
or
.asResponseInit()
to provide a body and headers to the client to establish
the event connection. This is accomplished by keeping a connection open to
the client by not closing the body, which allows events to be sent down the
connection and processed by the client browser.
See more about Server-sent events on MDN
Example
import {
ServerSentEvent,
ServerSentEventStreamTarget,
} from "https://deno.land/std@0.205.0/http/unstable_server_sent_event.ts";
Deno.serve({ port: 8000 }, (request) => {
const target = new ServerSentEventStreamTarget();
let counter = 0;
// Sends an event every 2 seconds, incrementing the ID
const id = setInterval(() => {
const evt = new ServerSentEvent(
"message",
{ data: { hello: "world" }, id: counter++ },
);
target.dispatchEvent(evt);
}, 2000);
target.addEventListener("close", () => clearInterval(id));
return target.asResponse();
});
Classes
An event which contains information which will be sent to the remote
connection and be made available in an | |
An implementation of |