How to receive UDP packets in Python without dropping
Question: I am writing simple software to parse MPEG-TS stream to check CC (cointinuity
counter) to see if any packets were dropped. When I run my script against file
it works flawlessly. But when using it on UDP stream it shows losses (which
are not confirmed by another software):

It is quite simple:

    
    
    while True:
        received = sock.recv(7 * 188)
        parsepacket(received)
    

I left out `parsepacket` function for clarity. It is just using bitstring to
analyzee packet bit by bit.

In my understanding while I run `parsepacket` function other UDP packets are
just ignored, because I am not doing `sock.recv` quick enough (on 5 Mbps
stream it should parse about 500 packets pers second).

I tried using `sock.makefile` but no luck. I get same results.

My idea is to have receiving thread running in background and another thread
continously parsing what it receives. But honestly I have no idea how (besides
putting it all in memory which would run out very quickly).


Answer: Without seeing your script, or how you're actually doing any of this, we won't
be able to help you. However, this is trivial if you use Python's `twisted`
library. Here's a simple example, taken from their [examples
page](http://twistedmatrix.com/documents/13.2.0/core/howto/udp.html#auto4):

    
    
    from twisted.internet.protocol import DatagramProtocol
    from twisted.internet import reactor
    
    
    class MulticastPingPong(DatagramProtocol):
    
        def startProtocol(self):
            """
            Called after protocol has started listening.
            """
            # Set the TTL>1 so multicast will cross router hops:
            self.transport.setTTL(5)
            # Join a specific multicast group:
            self.transport.joinGroup("228.0.0.5")
    
        def datagramReceived(self, datagram, address):
            print "Datagram %s received from %s" % (repr(datagram), repr(address))
            if datagram == "Client: Ping":
                # Rather than replying to the group multicast address, we send the
                # reply directly (unicast) to the originating port:
                self.transport.write("Server: Pong", address)
    
    
    # We use listenMultiple=True so that we can run MulticastServer.py and
    # MulticastClient.py on same machine:
    reactor.listenMulticast(8005, MulticastPingPong(),
                            listenMultiple=True)
    reactor.run()
    

You can parse each packet in the `def datagramReceived` function.

