TCP blocking socket - possibility of recv small amount of bytes in different packets

StackOverflow https://stackoverflow.com/questions/20869687

  •  23-09-2022
  •  | 
  •  

Вопрос

If the server sends 4 bytes

send(sock, buffer1, 4, 0);

And client waits for exactly 4 bytes

recv(sock, buffer2, 4, 0);

Is there a possibility that less than 4 bytes will be written to buffer2? No other send or recv was made before.

If there is no possibility, what's the maximum size of buffer that send can do, so that recv could get the same buffer size in one call.

Это было полезно?

Решение 2

From the man page for recv:

"These calls return the number of bytes received, or -1 if an error occurred.

For TCP sockets, the return value 0 means the peer has closed its half side of the connection."

As such recv is always allowed return all of the bytes sent, fewer than the bytes sent, or none of the bytes sent. You cannot assume anything simply because you happen to know what send is doing at the other end of the connection.

There is no way to guarantee that you can always get complete message.

Другие советы

There's no such thing as a "message", except what you delimit yourself.

REPEAT: THERE IS NO SUCH THING AS A MESSAGE.

TCP does not send messages, it sends an octet stream.

You need to send in a loop, in case there is a backlog of unacknowledged data and send does not use the whole buffer you passed in. You need to recv in a loop, in case the sending stack chunked it in an unexpected way. You need to delimit your messages (eg by prepending a network-endian length), so you can recover them properly.

Yes, there's this possibility. In fact, recv gives you as return value the amount of bytes received.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top