Winsock recv problems
First off I apologize if this is in the wrong forum. I know its a networking question but its specifically for windows.
I have coded my server to send the string "hello world\r\n\r\n"
My client attempts to read the string like so
Now when I call the "response" function it outputs the first character from the "hello world" string which is obviously a 'h' followed by 19 junk values. If I the call the "response" function again it manages to output "elloWorld".
char String = "1234567890123456789";
int RetVal = SOCKET_ERROR;
while (RetVal == SOCKET_ERROR)
RetVal = recv(Socket, String, strlen(String), 0);
cout << String << endl;
Any idea why this is happening?
Edit: Is there anyway that I can code it so instead of reading everything thats been sent in one go, can I loop through and read one character at a time until say the character '\r' is read? Thanks
> Any idea why this is happening?
The network does NOT guarantee that if you send "hello world" in ONE send() call that you will receive "hello world" in a single recv() call.
Message fragmentation and reassembly is a problem you need to address yourself when using a TCP connection, since it is a streaming protocol.
Contrast that with UDP which is a packet oriented protocol (and an unreliable one at that). Either you get the whole packet, or none of the packet.
> can I loop through and read one character at a time until say the character '\r' is read?
Yes you can do that if you want.
Wrap it up in a function called recvAWholeLikeLikeFgets() perhaps, so you don't have to keep doing it over and over.
Hi thanks for the reply. Unfortunately I have another problem now.
My server only ever receives messages sent to it once the client calls the CloseSocket method.
So this works fine (client code)
However the following doesn't
recv(variables); // Receive servers greeting
send(variables); // Send Command
Basically whats happening is the server sends its greeting which is received by the client fine. The client attempts to reply with send but server doesnt receive until client closes socket. Then the client blocks waiting for a reply that wont come.
recv(variables); // Reveive servers greeting (THIS LINE WORKS)
send(variables) // Send Command (Server does not receive this)
recv(variables) // Wait servers reply (Blocks here)
send(variables) // Reply to server (never executes)
Sorry for the lack of information as im off out now, if you need more detail i'll post more when i get back.
I think that maybe if i flush the stream after each client "send" command it might work. Is there a flush command for WinSock?