user3052078
user3052078

Reputation: 495

Udp readfrom until the end

Socket Used : udp

I have a client who sends 5000 bytes and a server with this code :

Client code :

cod = sendto (sFd, (void *) buffer, 5000, 0, (struct sockaddr *)
            &soc, sizeof (struct sockaddr_in));

Server code :

//leghtBuffer = 5000
while (lenghtBuffer > 0 )
{
 //I will insert a signal if pass more than 30 s ...
 cod = recvfrom (sFd, buffer,256 , 0, (struct sockaddr *) &clientSoc, &lungimeSocket); 

 printf("Am received %d bytes " ,cod );
 lenghtBuffer = lenghtBuffer - cod;

}

How can I read more than 1 time 256 bytes from this while (still using Udp socket)?

Upvotes: 0

Views: 777

Answers (1)

Joel Cunningham
Joel Cunningham

Reputation: 671

UDP is a message (datagram) based transport protocol and not stream based like TCP. Each sendto/recvfrom works in terms of complete messages.

On the sending end, each call to sendto() creates a datagram of the specified size and data, which in your case is 5000 bytes.

On the receiving end, each call to recvfrom() copies the next message in the receive buffer. Since your datagrams are 5000 bytes, but you're only providing a 256 byte buffer, your datagram is being truncated to 256 bytes as it's copied.

The recvfrom() OpenGroup specification clarifies the behavior in this case:

For message-based sockets such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message must be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes are discarded.

You'll want to increase your buffer on the receive end to be 5000 bytes to account for the entire datagram

Upvotes: 3

Related Questions