0

I have simple function that responsible on receiving packets via socket.

if((recv_size = recv(sock , rx , 50000 ,0)) == SOCKET_ERROR)
  {
    ...                         
  } else
  {
    ...
  }

I found that sometimes I receiv incompleate packet. Why? Mybe I should use recv for several times? Packet length never exceeds 50000 bytes.

I use TCP socket.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
vico
  • 17,051
  • 45
  • 159
  • 315
  • What kind of socket do you use ? UDP or TCP ? In TCP it might be required to use multiple times recv. – AdamF May 21 '15 at 08:10

1 Answers1

4

If you're using TCP it's expected. TCP is a streaming protocol, it doesn't have "packets" or message boundaries, and you can have received all of the "message" or part of it, or even multiple messages. So you might have to call recv multiple times to receive a complete message.

However, since TCP doesn't have message boundaries, you have to implement them yourself on top of TCP, for example by sending the length of the message in a fixed-size header, or have some special end-of-message marker.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • But what if no more data will come and I call recv once again. In this case I will wait forever this function return. – vico May 21 '15 at 14:23
  • @vico You should tell recv to only read until you have consumed all the data you expect which you would determine by reading a fixed-size length header or some end of message marker. If you're wondering how to handle waiting for more messages after you finish receiving the previous one, then you'll want to add threading to your server so you don't block while waiting for recv to return something. – chemdt May 21 '15 at 15:09
  • @vico If you have message boundaries or lengths in your protocol, then you can read the exact amount needed (possibly with multiple calls), or you can use e.g. `seelct` or `poll` to see when there is data to read without the receiving function blocking, or you could use non-blocking sockets. – Some programmer dude May 21 '15 at 15:57