Receiving Data in UDP Mode

In the previous section, we explained how to handle data reception when the socket is in the TCP mode. This section provides explanation for receiving data with UDP.


Using the on_sock_data_arrival Event

With UDP, you still (typically) process incoming data based on the on_sock_data_arrival event. Two differences apply:

Here is an example: Suppose that two datagrams are waiting in the RX buffer and their contents are "ABC" and "123"; the following code will then execute twice:

Tibbo BASIC
sub on_sock_data_arrival
dim s as string(2)
s = sock.getdata(255) ' will get 2 bytes as this is the capacity of s
end sub

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 the sock.nextpacket Method

Using the 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 in which we handle all incoming UDP data without exiting the event handler:

Tibbo BASIC
dim s as string
 
...
 
l1:
while sock.rxlen = 0
	doevents 'good practice: let other events execute while we are waiting
wend
 
sock.nextpacket 'Now we know that we do have data, 'move to' the next UDP datagram. This is like entering the on_sock_data_arrival. 
s = sock.getdata(255) 'get data
goto l1
 
...

Receiving Data in UDP Mode

Using the on_sock_data_arrival Event

Using the sock.nextpacket Method