1
votes

I've got a general question about the recv-function of winsock. I write a program with a client/server-architecture where the client sends a camera image to the server and the server sends another image back to the client. The client sends several images until the program is closed. And the server will responds every received image with an other image.

Client (send) ----> Server (receive) ----> Server (send) ----> Client (receive) . ^______________LOOP_____________________________|

My problem is the servers receive function. If I call the receive function several times with a 512Byte large buffer, how do I know that I received the whole image? The examples I found just wait until the connection is closed (recv returns 0), but I want to receive several images without closing the connection. But if I receive until there aren't any bytes left in the buffer, the recv function will halt the thread until there are new bytes (but this will never happen because the server first want to send its own image back to the client before receiving the next one).

So is there any possibility to tell the server that the whole image was received so that it can send its own image back to the client without waiting for the next bytes or a closed connection?

2

2 Answers

4
votes

Develop a protocol with a header which includes the size n of amount of data that the receiver has to expect. The receiver only reads the header PLUS n bytes (indicated by the header) from the TCP-stream. Then you can expect the next header. If you don't receive those n bytes, the transmission is incomplete.

In short you could define a message in your protocol as follows:

Message:

  • data length (32 bits, unsigned int)
  • data content
1
votes

wrap your image data in a packet consisting of

  • a fixed-size header telling how many bytes will follow
  • the actual image data

in your receive code you first read the header part, the read the appropriate amount of data.

example code with error checking omitted; also you must always loop the actual recv call since data might arrive in pieces!

unsigned bytesExpected;
Image imgData;
while( !LoopMustStop )
{
  Read( sizeof( unsigned ), bytesExpected );
  Read( bytesExpected, imgData );
  Process( bytesExpected, imgData )
}