Trevin Corkery Trevin Corkery - 3 months ago 17
HTTP Question

C++ - Sending HTTP POST/GET after connection has closed

I've been searching for a solution on StackOverFlow and couldn't seem to find an answer, I am using WinSock2 to log into a website and the server responds with "Connection: close" (Even if I send Connection: keep-alive) in the header. Any messages attempting to recv after returns 0. (0 = Graceful close)

Questions:


  1. Is the connection suppose to drop after a POST request?

  2. How do you send subsequent GET/POST requests after it has dropped?



So do you have to recycle the socket and re-establish everything again like my example below?

Example of list of events (that i'd imagine i'd need to do):


  1. WSAStartup

  2. Find Address

  3. Create socket

  4. Connect Socket with address

  5. Send Post Request



---Connection Closes after Post---


  1. Destroy Socket

  2. Create socket

  3. Connect Socket with address

  4. Send Get Request with Authentication Cookie



This is what I picture the event chain would look like, but I am not 100% sure how browsers handle all this. But I learn from other users experience and input so if anyone knows exactly what happens let me know. Thank you for your time,

Answer

Is the connection suppose to drop after a POST request?

It can, yes. HTTP is a stateless protocol, there is no guarantee that the connection will stay alive after a response, even if a keep-alive is requested. Whether or not to close the connection after sending the response is up to the server to decide, if the client does not request the connection to be closed.

How do you send subsequent GET/POST requests after it has dropped?

You have no choice but to reconnect to the server, and everything that involves (TCP handshakes, SSL/TLS handshakes, etc) before you can send the new request.

If you:

  • send an HTTP 1.0 request that does not explicitly state Connection: keep-alive, or receive an HTTP 1.0 response that does not explicitly state Connection: keep-alive

  • send an HTTP 1.1 request that explicitly states Connection: close, or receive an HTTP 1.1 response that explicitly states Connection: close

Then you must close your end of the connection after reading the response.

Even if the response indicates a keep-alive is in effect, the connection could still timeout and be closed before you send your next request on the same connection.

So, any time you want to send a new request, if the connection has already been closed previously, or you get a connection error while sending the request, close the socket, reconnect, and resend the request.

So do you have to recycle the socket and re-establish everything again like my example below?

Potentially, yes.

I am not 100% sure how browsers handle all this.

Exactly as described above.

This is discussed further in RFC 2616 Section 8 "Connections".

Comments