Skip to content

Detecting whether a client vanished #953

@Profpatsch

Description

@Profpatsch

Is there a way to detect whether a client has vanished during a request?

setOnClose will only fire at the very end as far as I can see.

The following code tries to use responseStream, and by flushing before every delay I hoped it would realize the client is gone:

bar :: IO ()
bar = Warp.runSettings
  ( Warp.defaultSettings
      & Warp.setPort 1234
      & Warp.setOnClose (\sockAddr -> print "connection vanished")
  )
  $ \req respond -> do
    respond $ Wai.responseStream ok200 [] $ \write flush -> do
      print "sleeping"
      traverse_
        ( \_ -> do
            flush
            print "loop"
            threadDelay 1_000_000
        )
        [1 .. 10]
      write "done"
      print "done"

When I run this and start a curl http://localhost:1234 which I Ctrl+c after ~1-2 seconds, it will print:

"sleeping"
"loop"
"loop"
"loop"
"loop"
"loop"
"loop"
"loop"
"loop"
"loop"
"loop"
"done"
"connection vanished"

regardless of my client going away.

There is an old-ish SO question that creates a workaround by trying to read from the client socket in regular intervals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions