Skip to content

Instantly share code, notes, and snippets.

@sandervandevelde
Created September 19, 2022 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandervandevelde/20a7affced37d4d3b6e5e2c6e8a9dab0 to your computer and use it in GitHub Desktop.
Save sandervandevelde/20a7affced37d4d3b6e5e2c6e8a9dab0 to your computer and use it in GitHub Desktop.
Hello @JanFlikweert-3331 ,
working with UDP can be challenging.
It seems you tried the 'blocking' version of working with UDP.
Have you tried the [async][1] version also?
I made a little adjustment to my project:
```
while (true)
{
messageBeingProcessed = true;
udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s);
while (messageBeingProcessed)
{
Thread.Sleep(5); // MUST BE LOWER THAN SERVER TIME
}
}
```
When a message is received, this 'messageBeingProcessed' is reset.
```
public static void ReceiveCallback(IAsyncResult ar)
{
try
{
UdpClient u = ((UdpState)(ar.AsyncState)).u;
IPEndPoint e = ((UdpState)(ar.AsyncState)).e;
byte[] receiveBytes = u.EndReceive(ar, ref e);
// do something with the received bytes.
}
finally
{
messageBeingProcessed = false;
}
}
```
This solution is sunning stable in our Azure IoT edge project.
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.udpclient.beginreceive?view=net-5.0&WT.mc_id=IoT-MVP-5002324
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment