I’ve been working with UDP sockets quite a lot recently. I’ve read that UDP does not have an internal buffer. That means if a packet arrives and there is no one waiting for it, it gets dumped. I’ve thought of a situation which’s occurence is very unlikely. But if it occurs, it can cause problems.
byte[] buffer = new byte[1024];
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(...);
while (true)
{
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
socket.ReceiveFrom(buffer, ref remote);
socket.SendTo(remote, new byte[] { 1, 2, 3, 4 });
}
What if while SendTo is executed, which is a non-async method (so it blocks the thread it’s run in until it’s done, i.e. done sending the data), another packet from a different host arrives? As the ReceiveFrom method is not being executed, will the packet get dumped?
Just assuming “yes”, I’ve thought of using asynchronous sockets. It would look like this:
Socket socket;
byte[] buffer;
void StartServer()
{
buffer = new byte[1024];
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(...);
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
StartReceive();
}
void StartReceive()
{
socket.BeginReceiveFrom(buffer, 0, buffer.Size, SocketFlags.None, ref remote, OnReceive, null);
}
void OnReceive(IAsyncState state)
{
EndPoint epRemote = new IPEndPoint(IPAddress.Any, 0);
socket.EndReceiveFrom(state, ref epRemote);
socket.BeginSendTo(new byte[] { 1, 2, 3, 4 }, 0, 4, SocketFlags.None, epRemote, null, null);
StartReceive();
}
When the OnReceive method is called by socket.BeginReceiveFrom when it’s done, its code gets executed. Since this code uses BeginSendTo, it doesn’t block the thread. But what if a packet arrives before OnReceive can call StartReceive? Will it be lost?
So my question:
Does a UDP packet get buffered at all, and if yes, for how long?
No, the internals of the framework will ensure that the packets are in a que until they get parsed. This is usually achieved by using a buffer that saves the packets for a period of time until the reciever actually gets the packets.
There are multiple layers that ensure this, for more information and because you use the application layer of OSI you should study OSI to understand these concepts deeply.