Created
March 2, 2026 20:43
-
-
Save jrosell/178ed4fab7189ed64f472b8e3bf3a068 to your computer and use it in GitHub Desktop.
HTTP streaming and Server-Sent Events in R with nanonext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # pak::pak("r-lib/nanonext") | |
| library(nanonext) | |
| 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") | |
| ) | |
| server <- http_server( | |
| url = "http://127.0.0.1:8080", | |
| handlers = handlers | |
| ) | |
| server$start() | |
| server$url | |
| # Open in two terminals | |
| # curl -X GET http://127.0.0.1:8080/stream | |
| # curl -X GET http://127.0.0.1:8080/stream | |
| # Send in another terminal | |
| # curl -X POST http://127.0.0.1:8080/broadcast -H "Content-Type: application/json" -d 'hello world' | |
| # Both clients recieve the message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment