In an attempt to detect clients closing their side of the SSE connection I use 
selectRead(fds) on the specific handle. When the connection is alive the result 
is 0, i.e. can't be read. When the client closes the connection the result is 
1. I have a hard time reasoning about this. Lack of knowledge. Is this a sound 
method for the purpose?

Then when I try to close the half open connection to the client on the server I 
get the error: `Exception message: Operation performed on a socket which has 
not been registered with the dispatcher yet.` and have no idea what that means.
    
    
    import asynchttpserver, asyncdispatch, asyncnet, nativesockets, net
    import times, strformat, random
    
    
    proc main {.async.} =
      var server = newAsyncHttpServer()
      proc cb(req: Request) {.async.} =
        let fd = int(req.client.getFd)
        let headers = {
          "Content-type": "text/plain; charset=utf-8",
          "Cache-Control": "no-cache",
          "Content-type": "text/event-stream; charset=utf-8",
          "Connection": "keep-alive",
          "Content-Length": ""
        }
        await req.respond(Http200, "", headers.newHttpHeaders())
        while true:
          var fds = @[req.client.getFd]
          let delay = rand(2000)
          let data = "event: test\ndata: next delay is {delay/1000} s\n\n".fmt
          await req.respond(Http200, data)
          var closed = selectRead(fds)
          echo "fd : ", fd, " closed : ", closed
          #if closed == 1:
          #  req.client.close()  #error not registered dispatcher
          await sleep_async(delay)
      
      
      server.listen Port(8088)
      while true:
        if server.shouldAcceptRequest():
          await server.acceptRequest(cb)
        else:
          poll()
    
    asyncCheck main()
    runForever()
    
    
    Run

simple python client; 
    
    
    import urllib.request
    
    req = urllib.request.Request(
        'http://192.168.1.4:8088/sse/',
        headers={
            "Accept": "text/event-stream",
            "User-Agent":"TeSt"
        },
        method='GET'
    )
    
    #url = 'http://192.168.1.4:8088/sse/'
    with urllib.request.urlopen(req) as response:
        print (response.url)
        print (response.headers)
        print (response.status)
        for line in response:
            print(line)
    
    
    Run

Reply via email to