Reputation: 101
I have data from socket, which is header and message. Header if of 5 bytes, 3rd and 4th is message length.
I am reading from socket, can someone suggest me good function, it will return me msg. assuming that i am reading 1024 bytes and it may happen that i have recived only partial data.
Upvotes: 0
Views: 287
Reputation: 229844
You should put the call to read()
/recv()
in a loop that you exit once you have read enough data. If only partial data is received, you should keep on reading again until you received enough to parse the packet.
Upvotes: 1
Reputation: 1503260
Why would you read 1024 bytes? Read 5 bytes, repeating the read if necessary until you've actually got 5 bytes (or an error). Then you know how long the message itself is: so repeatedly read until you've got all the data for the message. (On each call you only ask for as much data as you actually want, of course - so if when you're reading the header you first read 2 bytes, then on the next call you request 3 bytes, i.e. the remainder of the header.)
Reading more than you know you need is just asking for complexity - it means you've got to remember that data somewhere for the next read.
Upvotes: 1