waterlooalex
waterlooalex

Reputation: 13892

How should a HTTP server (using sockets) detect that the client is no longer connected and abort processing?

I'm implementing a basic HTTP Server in C++, using boost::asio.

As I process each request, I write out the data in chunks, asychronously. If at any point I knew the client was no longer connected, I'd like to abort the processing, e.g. there's no point continuing to build results up to send out if the client is no longer there.

I think this has already been asked here a few times, e.g.:

How can I check if a client disconnected through Winsock in C++?

But I reading them I'm still not sure what a good approach here is.

Upvotes: 0

Views: 1531

Answers (2)

nos
nos

Reputation: 229108

There are 3 things to consider (though how that's done using boost, I don't know)

  • Detect a clean shutdown from the client. This is done by a read() from the client. a read returning 0 means the other end have closed the connection, if you're implementing http pipelining you likely have to keep reading from the client anyway.

  • Detect an unclean shutdown on the client, a write() should eventually fail, a read() will error as well

Then there's the cases inbetween where the client just vanishes or is a maliciously slow reader/writer You'll have to implement;

  • Timeouts. if there's no activity for a period of time you should throw away the connection. This applies you writing something to the client as well. Any network read or write that doesn't implement a timeout is severely broken anyway, and will end up leaking resources (Just think users closing their notebook, pulling the cable, NAT gateways silently throwing away tcp connections , malicious users not reading and blocks the TCP transfer, etc.). If you have no control over the async write process, you'll get in trouble here.

Upvotes: 0

bdonlan
bdonlan

Reputation: 231193

If the client disconnects, you should have your asynchronous writes fail with an appropriate error code. When your completion handler is invoked with an error, abort processing then.

Upvotes: 1

Related Questions