notiggsam
notiggsam15mo 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
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
notiggsam
notiggsam15mo 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
NDH15mo 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
NDH15mo 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
notiggsam15mo 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.
𝕒𝕣𝕤𝕙
𝕒𝕣𝕤𝕙15mo ago
there's no standard for a server-side api
ioB
ioB15mo ago
There's nothing super special about the SSE api. It looks like skye made a polyfill at https://deno.land/x/eventsource
𝕒𝕣𝕤𝕙
𝕒𝕣𝕤𝕙15mo 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