Back
+20 XP
Concept

Server-Sent Events (SSE) for Real-Time Streaming

Server-Sent Events (SSE) stream unidirectional real-time data over a persistent HTTP connection using `Content-Type: text/event-stream`. Simpler than WebSockets for live tickers and notifications 🌊.

python
import json

def format_sse(event_name: str, payload: dict) -> str:
    return (
        f"event: {event_name}\n"
        f"data: {json.dumps(payload)}\n\n"  # Double newline terminates event frame! 🌊
    )

frame = format_sse("price_update", {"ticker": "AAPL", "price": 182.50})
print(frame)

# 40. Server-Sent Events (SSE) for Real-Time Streaming Server-Sent Events (SSE) stream unidirectional real-time data over a persistent HTTP connection using `Content-Type: text/event-stream`. Simpler than WebSockets for live tickers and notifications 🌊. ```python import json def format_sse(event_name: str, payload: dict) -> str: return ( f"event: {event_name}\n" f"data: {json.dumps(payload)}\n\n" # Double newline terminates event frame! 🌊 ) frame = format_sse("price_update", {"ticker": "AAPL", "price": 182.50}) print(frame) ``` Modern LLM token streaming (like ChatGPT or Gemini API streaming completions) uses this exact Server-Sent Events format! 🌊 --- ### Question What delimiter marks the completion of an SSE message frame in `text/event-stream`? 🧠 - [ ] a. Two consecutive newline characters (`\n\n`) 🌊 - [ ] b. `END_FRAME` - [ ] c. A zero-byte `\0` - [ ] d. A closing XML tag --- ### Challenge Write a function `sse_ping(timestamp)` that outputs formatted SSE string with `event: ping\ndata: {"time": <timestamp>}\n\n`. Call with `123456` and print. 🎯 <details> <summary>Solution</summary> ```python import json def sse_ping(timestamp): data_str = json.dumps({"time": timestamp}) return f"event: ping\ndata: {data_str}\n\n" print(sse_ping(123456).strip()) ``` </details>

Checkpoint

What delimiter marks the completion of an SSE message frame in `text/event-stream`? 🧠

Practice

Write a function `sse_ping(timestamp)` that outputs formatted SSE string with `event: ping\ndata: {"time": <timestamp>}\n\n`. Call with `123456` and print. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks