2
votes

I wrote a simple C socket program that sends an INIT package to the server to indicate to prepare a text transfer. The server does not sends any data back at that time. After sending the INIT package the client sends a GET package and waits for chunks of data from the server. So every time the server receives a GET package it will send a chunk of data to the client.

So far so good. The buffer has a size of 512 bytes, a chunk is 100 Bytes plus a little overhead big.

But my problem is that the client does not receive the second message.

So my guess is that read() will blpck until the buffer is full. Is that right or what might be the reason for that?

3
No, read() would read whatever it has. It will block only in blocking mode, when there is no data and no other events pending. - Valeri Atamaniouk
Thanks. Then what could be the problem? Could it be that the 2nd message was send too fast? - user5444681
No. Even if it is sent before the client sent it's data, you would be able to read it, as it is the way stream sockets operate. It might be so, that the server has not received full request and thus doesn't send response. For example, in HTTP protocol, the server would not start replying until it reads all request headers + newline. So check that part. - Valeri Atamaniouk
So do I have to add a special char like \n? I didn't. - user5444681
If you use HTTP, the end of request is two '\n' chars (to make one empty line). I don't recommend you to implement own HTTP stack. Use some existing library instead. HTTP protocol is a bit cumbersome and has a lot of nuances. Otherwise, read w3.org/Protocols/rfc2616/rfc2616.txt - Valeri Atamaniouk

3 Answers

1
votes

It depends. For TCP sockets read may return before the buffer is full, and you may need to receive in a loop to get a whole message. For UDP sockets the size you read is typically the size of a single packet (datagram) and then read may block until it has read all the requested data.

1
votes

The answer is no: read() on a tcp/ip socket will not block until the buffer has the amount of data you requested. read() will return immediately in all cases if any data is available, even if your socket is blocking and you've requested more data than is available.

Keep in mind that TCP/IP is a byte stream protocol and you must treat it as such. The interface is under no obligation to transmit your data together in a single packet, as long as it is presented to you in the order you placed it in the socket.

-4
votes

The answer is no , read is not blocking call , You can refer below points to guess the error

Several Checkpoints you can find :

  1. Find out what read is returning at the second time .
  2. memset the buffer every time in while before recv
  3. use fflush(stdout) if not able to output.

Make sure all three are present . if problem not solved yet .please post source code here