Created
September 19, 2022 20:09
-
-
Save sandervandevelde/20a7affced37d4d3b6e5e2c6e8a9dab0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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