4

I'm using the recv function in a loop to receive network data, but let's say I want to stop receiving data mid-loop. I could just break the loop, but this doesn't seem like a very clean way to stop receiving data.

So is there any way to cleanly stop receiving data, or is just breaking the loop ok? It's HTTP GET/POST requests.

Here's simplifed I'm using:

do {
  nDataLen = recv(mySocket, data, BUFFSIZE, 0);
  if (nDataLen > 0)
  {
    /* Process Data */
    // I'd like to break out of the loop
    // if something is found when processing the data
    // But, I want to do this cleanly.
  }
} while (nDataLen != 0);
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Josh
  • 6,046
  • 11
  • 52
  • 83
  • Can we see the code you're using? – Brendan Long Sep 30 '11 at 04:39
  • What do you mean by "stop receiving data"? recv allows you to pull data out of the network buffers that has been received, or to wait until some data has been received. If you don't call recv, that doesn't mean that the data isn't being received. It still goes into a system buffer somewhere. – Vaughn Cato Sep 30 '11 at 04:44
  • @VaughnCato Would it hurt anything to just break the loop? If the data is in a system buffer somewhere, how long does it stay there? – Josh Sep 30 '11 at 04:47
  • 2
    @Josh: No that is fine. It will stay there until you do get it using another recv() or you close the socket. – Vaughn Cato Sep 30 '11 at 04:54

3 Answers3

3

Breaking out of the recv loop won't close the connection. All that happens is that you stop calling recv and therefore stop reading data from the socket. Data from the peer will still be arriving on your socket. If you want to cleanly shutdown then call close on the socket file descriptor.

sashang
  • 11,704
  • 6
  • 44
  • 58
0

Breaking out of the loop is a way of stop calling recv. Another is to include a boolean should_stop and check for it in the loop condition. You should however receive whatever is left in the socket and properly close it.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

If you don't need the socket close the socket and break out of loop.

Vineet G
  • 175
  • 1
  • 1
  • 8