pythonsocketsudprecvfrom

Avoid accumulation of data in udp socket or read newest data from udp socket


I am trying to send data continuously from a c++ code to a python code. I used udp sockets to send the data. The rate of sending is at a faster rate than the receiving rate as it is a simple sensor code. So the data sent is accumulated in the socket. When I try to read the data it returns an old data. How can I read the newest data from the socket or delete the old data when the new data is sent?


Solution

  • How can I read the newest data from the socket or delete the old data when the new data is sent?

    Read a packet of data from the socket and place it into a buffer. Keep reading packets from the socket, placing each packet into the buffer each time (replacing whatever packet-data was in the buffer previously), until there is no more data left to read -- non-blocking-I/O mode is useful for this, as a non-blocking recv() will throw a socket.error exception with code EWOULDBLOCK when you've run out of data in the socket's incoming-data-buffer. Once you've read all the data, whatever is left in your buffer is the newest data, so go ahead and use that data.

    Sketch/example code follows (untested, may contain errors):

      sock = socket.socket(family, socket.SOCK_DGRAM)
    
      [... bind socket, etc... ]
    
      # Receive-UDP-data event-loop begins here
      sock.setblocking(False)
      while True:
         newestData = None
    
         keepReceiving = True
         while keepReceiving:
            try:
               data, fromAddr = sock.recvfrom(2048)
               if data:
                  newestData = data
            except socket.error as why:
               if why.args[0] == EWOULDBLOCK:
                  keepReceiving = False
               else:
                  raise why
    
         if (newestData):
            # code to handle/parse (newestData) here