# NDJSON streaming endpoint
h <- handler_stream("/stream", function(conn, req) {
conn$set_header("Content-Type", "application/x-ndjson")
conn$send('{"status":"connected"}\n')
})
# SSE endpoint with reconnection support
h <- handler_stream("/events", function(conn, req) {
conn$set_header("Content-Type", "text/event-stream")
conn$set_header("Cache-Control", "no-cache")
last_id <- req$headers["Last-Event-ID"]
# Resume from last_id if client is reconnecting
conn$send(format_sse(data = "connected", id = "1"))
})
# Long-lived streaming with broadcast triggered by POST
conns <- list()
handlers <- list(
handler_stream("/stream",
on_request = function(conn, req) {
conn$set_header("Content-Type", "application/x-ndjson")
conns[[as.character(conn$id)]] <<- conn
conn$send('{"status":"connected"}\n')
},
on_close = function(conn) {
conns[[as.character(conn$id)]] <<- NULL
}
),
# POST endpoint triggers broadcast to all streaming clients
handler("/broadcast", function(req) {
msg <- paste0('{"msg":"', rawToChar(req$body), '"}\n')
lapply(conns, function(c) c$send(msg))
list(status = 200L, body = "sent")
}, method = "POST")
)
Run the code above in your browser using DataLab