Receiving Data in UDP Mode
|Top Previous Next|
In the previous section we have already explained how to handle data reception when the socket is in the TCP mode. This section provides explanation for receiving data with UDP.
Using on_sock_data_arrival event
With UDP, you still (typically) process incoming data basing on the on_sock_data_arrival event. Two differences apply:
Here is an example: supposing, two datagrams are waiting in the RX buffer and their contents are "ABC" and "123". The following code will then execute twice:
Since s has a maximum capacity of 2 the first time s=sock.getdata(255) executes you will get "AB". When the event handler is exited the rest of the first UDP datagram will be discarded, so next time you will get "12"!
Using sock.nextpacket method
Using on_sock_data_arrival event is a preferred method of handling an incoming data stream. Still, in selected cases you may need to process RX data in a loop, without leaving the event handler.
The sock.nextpacket method exists for just such a case. The result of this method execution is equivalent to exiting/(re)entering the on_sock_data_arrival event handler: the unread portion of the previous UDP datagram is discarded and we move to the next UDP datagram (if any).
Here is a code example where we handle all incoming UDP data without exiting event handler: