Brian Brown
Brian Brown

Reputation: 4311

How to ensure whole data was sent? sendto (udp socket) Python

First of all, I know the difference between TCP and UDP, and I know, that it's possible that some packets can be lost while using UDP.

However, when we assume that I designed a protocol with some simple ACK's for UDP, how can I ensure that I sent / received whole data?

For instance, with TCP sockets it's quite simple:

Receive:

def recvall(sock, n): 
    i = 0
    data = ""
    while i < n:
          data += sock.recv(1)
          i += 1
    return data

And send: sock.sendall(msg).

How something similar should be done while using UDP sockets?

Upvotes: 2

Views: 1680

Answers (1)

Son of a Sailor
Son of a Sailor

Reputation: 935

If you want ensure that your client receives all data, use TCP. UDP is not meant to be used in cases where you need to ensure data integrity. Only use UDP when it is acceptable to have dropped packets.

Now that being said, you can check if the client received all the data by putting sequence numbers in your UDP packets. Your client could then check each incoming packet's sequence number and compare it against the last sequence number it saw. If current_packet_sequence_num != last_packet_sequence_num + 1 then you can assume your client did not receive all data.

Upvotes: 4

Related Questions