Detect closed connection using StreamFdMessageReader?

74 views
Skip to first unread message

SR D

unread,
Feb 3, 2022, 11:47:22 AM2/3/22
to Cap'n Proto
Hi,

I use capnp::StreamFdMessageReader(fd) to read a message on a file descriptor created using network sockets.

And it works fine. However, I'm trying to detect if the client socket has closed. Normally, if a read() call returns 0, this would show the client connection has closed.

How would I go about this by using StreamFdMessageReader?


Kenton Varda

unread,
Feb 3, 2022, 3:52:32 PM2/3/22
to SR D, Cap'n Proto
So, StreamFdMessageReader was designed to read one message from an FD. It doesn't really have any way to say "try to read a message, but let me know if it's EOF".

Things you could do instead:
- Use poll() to check for POLLHUP before constructing StreamFdMessageReader. If POLLHUP is indicated, use ioctl FIONREAD to check if there are any bytes waiting to be read. If there are not, then you're at EOF, so don't create a StreamFdMessageReader at all.
- Wrap the FD in an kj::FdInputStream, and wrap that in kj::BufferedInputStreamWrapper. That lets you call `tryGetReadBuffer()` which will return null on EOF. `tryGetReadBuffer` doesn't actually advance the read pointer, it "peeks" at the next bytes in the stream, so if it returns a non-empty array, you can then use InputStreamMessageReader parse the message.
- Use KJ's async I/O, in which case you can use capnp::tryReadMessage() from capnp/serialize-async.h. This attempts to read a message but returns null on EOF.

Admittedly, these are all work-arounds for a missing API. We really should have a way to use StreamFdMessageReader but have it tell you if the stream was EOF...

-Kenton

--
You received this message because you are subscribed to the Google Groups "Cap'n Proto" group.
To unsubscribe from this group and stop receiving emails from it, send an email to capnproto+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/capnproto/c5b44e93-dde3-41ec-bced-7d839fde6185n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages