In @alexeypetrushin example with the asynchttpserver lib, I replaced the "for"
loop code with a "while". So I can test if the client is closed. But when I
close the browser, the server continues to send the response to the client.
Does the
[isclosed](https://nim-lang.org/docs/asyncnet.html#isClosed%2CAsyncSocket)
function detect when the connection to the browser is closed?
import httpcore, asyncdispatch, strformat, asynchttpserver, asyncnet
proc cb(req: Request): Future[void] {.async.} =
let headers = newHttpHeaders(@[
("Content-Type", "text/event-stream"),
("Cache-Control", "no-cache"),
("Connection", "keep-alive"),
# ("Connection", "close"),
("Access-Control-Allow-Origin", "*"),
("Content-Length", "") # To prevent AsyncHttpServer from adding
content-length
])
await req.respond(Http200, "200", headers)
# for i in 1..5:
var i = 0
while not req.client.isclosed():
echo "I'm alive ", $i
let msg = "data: " & $i & "\n\n"
await req.respond(Http200, msg)
await sleep_async(1000)
inc(i)
# req.client.close() # <= closing, otherwise it's going to be kept alive
and
# EvenSource in Browser won't reconnect automatically
var server = new_async_http_server()
async_check server.serve(Port(5000), cb, "localhost")
echo "started"
run_forever()
Run