notiggsam
notiggsam16mo ago

Server Sent Events with Fresh

Hi! I am trying to use Server Sent Events (SSE) with fresh. I understand I should have an island that holds the connection to the server but how can I broadcast the notifications to other islands?
9 Replies
again
again16mo ago
Using server-sent events - Web APIs | MDN
Developing a web application that uses server-sent events is straightforward. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events. This is a one-way connection, so you can't send events from a client to a server.
notiggsam
notiggsam16mo ago
My question was about client-side with Fresh's islands. On server side you don't need any particular support, as it is plain HTTP. You just have to stream your events with content-type: text/event-stream
NDH
NDH16mo ago
Client side would use an EventSource to subscribe to the stream, and POST to the server to publish messages. When you say other islands, do you mean other islands in the same browser tab, or other instances of the Deploy isolate, or other instances of the same deploy isolate in different browser tab? If same tab, just us browser BroadcastChannel. If different isolates, use Deno BroadcastChannel on the server.
NDH
NDH16mo ago
The following api code uses SSE + BroadcastChannel as a WRTC signalling service to connect two players over a WebRTC-Datachannel. https://github.com/nhrones/FreshDiceRTC/tree/master/routes/api
notiggsam
notiggsam16mo ago
Thank you @ndh3193 ! I would never have thought about using BroadcastChannel, I will definitely try it. My use case was different islands in the same tab.
𝕒𝕣𝕤𝕙
𝕒𝕣𝕤𝕙16mo ago
there's no standard for a server-side api
ioB
ioB16mo ago
There's nothing super special about the SSE api. It looks like skye made a polyfill at https://deno.land/x/eventsource
𝕒𝕣𝕤𝕙
𝕒𝕣𝕤𝕙16mo ago
yep it's just a ReadableStream i made a stream-like abstraction for it
const readableStream = serverSentEvents(async sendEvent => {
sendEvent('message one')
...
sendEvent('message two')
sendEvent(0)
})
const readableStream = serverSentEvents(async sendEvent => {
sendEvent('message one')
...
sendEvent('message two')
sendEvent(0)
})
worth noting this allows deno to read a SSE from another server, like the Web API, rather create and send its own