UDP
UDP sends separate messages without a connection. This lesson sends datagrams between two sockets of your own computer, answers the sender, waits with a time limit, and shows that UDP can lose data without telling anyone.
What you will learn#
- the difference between UDP (messages) and TCP (a stream),
UdpClient:Send,Receive,ReceiveAsync,Available,- binding to a port, and reading the port the system chose,
- answering the sender,
- a time limit with
Task.Wait(ms), - why a program that uses UDP must expect lost messages.
The tutorial Sockets used TCP: a connection, then a stream of bytes. UDP has no connection. Everything in this lesson runs on 127.0.0.1, so it works without a network.
The program#
# UDP - datagrams between two sockets of this computer, Receive with a time limit, broadcast-style replies and lost data
load "dotnet.ring"
using {
"System"
"System.Net"
"System.Net.Sockets"
"System.Text"
}
func main
oUtf8 = new UTF8Encoding()
oLoop = new IPAddress().Loopback
# 1. UDP sends separate messages (datagrams) without a connection: no Accept, no stream. A socket that listens binds to a port
# (0 = the system chooses a free one); LocalEndPoint tells which.
oServer = new UdpClient().@New([ :port = 0 ])
nPort = oServer.Client.LocalEndPoint.Port
? "1. the server socket is bound to a port: " + (nPort > 0)
# 2. The client sends three datagrams. Each Send is one message, and each Receive on the other side returns ONE message, not a
# part of a stream (TCP has no such borders).
oClient = new UdpClient()
for cText in ["one","two and more","three"]
aBytes = oUtf8.GetBytes(cText)
oClient.Send([ :dgram = aBytes, :bytes = len(aBytes), :hostname = "127.0.0.1", :port = nPort ])
next
? nl + "2. three datagrams sent; the server has data waiting: " + oServer.Available
for i = 1 to 3
oRemote = new IPEndPoint(oLoop,0)
aGot = oServer.Receive(oRemote)
cData = aGot[1]
? " datagram " + i + ": '" + oUtf8.GetString(cData) + "' (" + len(cData) + " bytes)"
next
# 3. A reply goes to the address of the sender. ReceiveAsync gives a result with the data (Buffer) and the sender (RemoteEndPoint).
oClient.Send([ :dgram = oUtf8.GetBytes("ping"), :bytes = 4, :hostname = "127.0.0.1", :port = nPort ])
oTask = oServer.ReceiveAsync(NULL)
oTask.Wait(NULL)
oResult = oTask.Result
? nl + "3. the server got '" + oUtf8.GetString(oResult.Buffer) + "' from the port of the client socket: " + (oResult.RemoteEndPoint.Port > 0)
cAnswer = oUtf8.GetBytes("pong")
oServer.Send([ :dgram = cAnswer, :bytes = len(cAnswer), :endPoint = oResult.RemoteEndPoint ])
oTask2 = oClient.ReceiveAsync(NULL)
oTask2.Wait(NULL)
? " the client got '" + oUtf8.GetString(oTask2.Result.Buffer) + "'"
# 4. UDP does not promise delivery. Nothing is waiting now, so a Receive with a time limit ends without data:
# ReceiveAsync + Wait(ms) answers false when nothing arrived.
oTask3 = oServer.ReceiveAsync(NULL)
lGot = oTask3.Wait(300)
? nl + "4. waited 300 ms with no sender: a datagram arrived = " + lGot
# 5. A datagram sent to a port where nobody listens is lost without an error on the sender's side
oClient.Send([ :dgram = oUtf8.GetBytes("anyone?"), :bytes = 7, :hostname = "127.0.0.1", :port = 9 ])
? nl + "5. sent to port 9 where nobody listens: no error, the data is just gone"
oServer.Close()
oClient.Close()1. the server socket is bound to a port: 1
2. three datagrams sent; the server has data waiting: 20
datagram 1: 'one' (3 bytes)
datagram 2: 'two and more' (12 bytes)
datagram 3: 'three' (5 bytes)
3. the server got 'ping' from the port of the client socket: 1
the client got 'pong'
4. waited 300 ms with no sender: a datagram arrived = 0
5. sent to port 9 where nobody listens: no error, the data is just goneThis program uses a generic function (getProp) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Datagrams#
A UDP message is called a datagram. It is sent in one piece and received in one piece: three Send calls give three Receive results of 3, 12 and 5 bytes, never a joined or a half message (a TCP stream has no such borders). There is no Accept and no stream; a socket that wants to receive only needs a port. new UdpClient([ :port = 0 ]) binds to a port that the system chooses, and Client.LocalEndPoint.Port tells which one. Texts are sent as bytes (UTF8Encoding.GetBytes) and read with GetString.
Sending#
Send has several forms, so it takes names: the bytes (:dgram), their count (:bytes) and the target (:hostname and :port, or an :endPoint). Available is the number of bytes waiting; after three datagrams of 3, 12 and 5 bytes it is 20.
Receiving#
Receive fills an IPEndPoint with the address of the sender (a ref parameter). In Ring the method returns a list: the data is the first item. ReceiveAsync is the task version; its result is read with getProp("Result") and has the data (Buffer) and the sender (RemoteEndPoint) (Core concepts, Plain objects).
Answering#
The sender's address is in the received datagram, so an answer is a Send to that RemoteEndPoint. The client socket sent without binding, so the system gave it a port; the server found it in the datagram.
Time limits and lost data#
Receive waits for ever when nothing comes. ReceiveAsync plus Wait(300) gives a time limit: false means nothing came in 300 ms. A program that talks by UDP must expect that. A datagram can be lost, doubled or delivered in another order, and the sender is not told: step 5 sends to a port where nobody listens, and there is no error. If you need every message in order, use TCP; if you need speed and can live with losses (games, sensor values, name lookups, discovery on a local network), use UDP, and add a counter and a timeout with a resend where it matters.
Do not leave an unfinished ReceiveAsync when you close a socket in a real program: cancel it, or close the socket and catch the error that the waiting task then raises.
What you learned#
- UDP sends messages; TCP sends a stream,
UdpClient.Send,Receive,ReceiveAsync,Available,- answering to the sender's endpoint,
- a time limit for a receive,
- UDP gives no promise of delivery.
Exercises#
- Write a small time server: it answers every datagram
timewith the current time. - Send 100 numbered datagrams quickly to a socket that is slow to read and count how many arrive (on one computer the answer is usually all of them: why is that no proof for UDP in general?).
- Add a resend: the client sends, waits 200 ms for an answer and tries three times.
- Send a datagram larger than 1500 bytes and look at what
Receivereturns.