BroadcastChannel vs EventSource vs WebSocket
Why would one uses BroadcastChannel, over EventSource, or WebSocket?
Could anyone provide clear examples, advantages, and inconvenient of them?
Are they all available on Deno Deploy?
4 Replies
The
BroadcastChannel
, EventSource
, and WebSocket
are all different APIs that serve different purposes, and they are all available in Deno.
1. BroadcastChannel
: This API is used for communication between different instances of your Deno Deploy script running in different data centers around the world. It's a simple message bus that connects the various Deploy instances worldwide. It's useful in real-time applications like chats and games. For example, you can use BroadcastChannel
to build a simple chat system where messages sent in one region are received in all other regions. However, it's important to note that this API is still experimental and may change in the future.
2. EventSource
(Server-Sent Events): This API is used for one-way communication from the server to the client. The server can send events to the client at any time. This is useful for applications that need real-time updates from the server, like a live news update or a real-time dashboard. Note that Deno Deploy uses HTTP/2, so Server-Sent Events do not suffer from the browsers maximum open connections limit that makes SSE over HTTP/1.1 unwise.
```javascript
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
const msg = new TextEncoder().encode("data: hello\r\n\r\n");
serve(async (_) => {
let timerId: number | undefined;
const body = new ReadableStream({
start(controller) {
timerId = setInterval(() => {
controller.enqueue(msg);
}, 1000);
},
cancel() {
if (typeof timerId === "number") {
clearInterval(timerId);
}
},
});
return newResponse(body, {
headers: {
"Content-Type": "text/event-stream",
},
});
});
The AI bot got it down pretty well. Feel free to ask more questions.
I like SSE+BC
The SSE has auto-reconnect, and BC bridges all clients across isolates and regions.
A very simple SSE-Chat example:
https://github.com/nhrones/SSE-CHAT
![No description](https://cdn.answeroverflow.com/1174867253431386174/comms.png)