views:

54

answers:

2

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.

+1  A: 

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.

Jon Skeet
Can u suggest code in C, first i will read first 5 bytes, i.e header, take msg length, and read get my msg. now again i will read 5 bytes read header and again msg, is that you are suggesting
@user363638: I'm not going to write the code for you (it's a while since I've done C, and I'd have to look everything up) - which bit of the suggestion are you finding hard? Do you know how to read from the socket? Do you know how to use the return value? Do you know how to convert the header into a message length?
Jon Skeet
+1  A: 

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.

sth