How to check for a closed socket

N

Nuno Magalhaes

How to check for a closed http socket without losing any data? (MSDN
says to send something to server).
Somewhere in my code (after sending the http header in plain text) I'm
doing a loop with:
Loop:----------------
Socket.Receive //receive http data chunks
Socket.Send //'/r/n' data to check if connection is active
------------------------
The problem is that when connection is closed by the http server, the
send socket function will throw an exception and it is impossible to
receive the last bytes if the data arrives between Socket.Receive and
Socket.Send functions.

How to check for a closed http socket without losing any data? This
must be easy to explain. Someone must have done this... what is the
solution?
(My solution wasn't sending nothing at all, but instead searching for
the "</html>" tag in the bytes received... but that is a slow procedure
and may give deadlock if the main page has no "</html>" tag.)

Thanks for any response,
Nuno Magalhaes.
 
V

Vadym Stetsyak

Generally it is not needed to check if connection is available. You can set
keepalive socket option, in order to maintain connection opened.

If server sent data and was forcibly closed you have no way to receive your
data, because only sender of the data can resend then ::cool:

Hmm, if you may have deadlock I would recommend you to redesign the
algorithm.
For example you can search for a </html> on the other thread.
Generally it is recommended not to put time consuming work into the same
thread where network I/O is held...
 
N

Nuno Magalhaes

But it is not me who closes the connection after sending the data, it
is the server! (as described in the HTTP RFC for "Connection: close"
parameter).

The server send all the data in chunks of 8192 bytes I guess but the
last bytes I can't get it because I make a "send" to the server to
check if it is alive and it isn't. After that "send" I can't receive
anymore... but only after a failed "send".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top