Tutorial 4: Using UDP
Adapted from Spectranet: Tutorial 4.
UDP is datagram-based rather than stream-based. A call to sendto sends one packet, and recvfrom receives one packet. The protocol does not guarantee delivery, ordering, or duplicate suppression.
When UDP fits
UDP is useful when:
- the whole message fits in one packet
- delayed data is no longer useful
- the application has its own reliability rules
- many remote peers need to communicate through limited local resources
DNS, DHCP, and many multiplayer game protocols are common UDP examples. If the program starts adding a general retransmission and ordering layer, TCP may be the better choice.
Server flow
A UDP server normally:
- opens a
SOCK_DGRAMsocket - binds it to a local port
- waits for datagrams with
recvfrom - replies to the address returned by
recvfromusingsendto - closes the socket when finished
There is no listen or accept step for UDP. The server learns the remote endpoint only when a datagram arrives.
Client flow
A UDP client opens a datagram socket, prepares the remote address and port, then sends messages with sendto. It can wait for replies with recvfrom.
Because UDP has no connection teardown, servers often use explicit handshakes or timeouts to decide when client-side state can be discarded.
Opening a UDP socket
In C:
int sockfd;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
In assembly:
ld c, SOCK_DGRAM
ld hl, SOCKET
call HLCALL