Tech Support > Microsoft Windows > Development Resources > recv problem.
recv problem.
Posted by Flzw on August 5th, 2004


I use recv to get messages from a server, every messages are separated by
\r\n combination

Here is my loop to receive the messages :

while( ((trbytes = recv( Socket[0], RcvBuf, 8192, NULL)) != 0) && (trbytes
!= SOCKET_ERROR))
{
int offset = 0;
int i = 0;
while( offset < trbytes )
{
if ( (RcvBuf[offset] == '\r') && ( RcvBuf[offset + 1] == '\n'))
{
msg[i] = '\r';
msg[i+1] = '\n';
ProcessMessage( msg);
i=0;
offset += 2;
}
msg[i++] = RcvBuf[offset++];
}
}

Which works very well, the only problem is when the server sends a lot of
messages in a short period of time, at some point (which is always the same
for each servers) there are some bytes lost, like 4 or 12 at the start of
the recv buffer, they should be there, but they are not.
The strange thing is if I run it steps by steps on debug, it works, they are
there... I first thought that my buffer was full and thoses bytes were
clipped by the previous recv but as you can see the buffer is 8k and I never
went passed 3k at a time while having this bug.

I don't know if I made myself clear :/ but I'm quite lost here. Any clues
will be appreciated.


Posted by Scott McPhillips [MVP] on August 6th, 2004


Flzw wrote:
(1) You need an else. When '\r' is found offset increments by 3.

(2) This code assumes that recv will only return whole messages. Not
true! It returns an arbitrary number of bytes, unrelated to message size.

Suppose recv gives you 1.5 messages. After copying the 0.5 fragment the
outer loop zeros i, so your code then overwrites the fragment.

--
Scott McPhillips [VC++ MVP]


Posted by Flzw on August 6th, 2004



Hmm, I must have been high or something when I wrote this :/

Thanks a lot!