Alex F
Alex F

Reputation: 43311

Reading UDP socket: records or stream

Let's say that UDP sender executes sendto several times:

sendto(s, buffer, 100, ...);
sendto(s, buffer, 200, ...);
sendto(s, buffer, 300, ...);

Receiver executes the following code when data is available:

void OnReceive()
{
    recvfrom(s, buffer, 1000, ...);
}

Now, if all data (100+200+300) is available when recvfrom is called, is it possible that it will be read by one recvfrom call, or several recvfrom calls with unpredictable sizes? Or it will be always received by the same portions as it was sent: 100, 200, 300?

To write 100% correct receiver code, should I implement kind of stream parsing logic, or data records reading logic?

For this question, I assume that data is not lost and packets order is not changed, though, in general case, this is not correct for UDP sockets.

Upvotes: 1

Views: 916

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

One read from UDP socket dequeues one datagram no matter how many are in the queue (exception being new Linux-specific recvmmsg(2) API), i.e. assuming packets are not reordered and the buffers you give to the kernel are big enough, you'll get 100, 200, and 300 bytes in three reads.

UDP applications are usually record-oriented.

Upvotes: 2

Related Questions