I have an application in which various entities communicate to each other via sockets and I'm using the C programming language. When an entity sends a long message to another entity, the recv() function may read this message in parts. Therefore, I have to re-construct the message on the recipient side by appending all the received parts.
My question is a general socket programming question related to recv(). How does recv() know when a message has been fully read? Should I terminate a message with a special character like "\n"? or should I send the size of the message as a header? What is the common practice?
As you've noticed, with stream sockets there is no built-in notion of message boundaries. You need to build some way of determining the end-of-message into your application-level protocol.
Both of the options you've suggested are common: either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.
When you use send() and recv() you specify a buffer size.
If you are using such a way to send a message:
send(new_socket,message,strlen(message),0);
The third parameter is the size of your buffer.
One way to learn if you have sent a packet successfully is if you are using TCP sockets, send()
and recv()
would return the same values. You can check this at the sender side by checking if the message size is the same as the value returned from send()
.
For checking at the receiver side, easiest way is to add end of string delimiter \0
to your string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With