I am relatively new to UDP. I am trying to write some code in a function that checks if I am receiving data on a UDP port, so I can change an element to show the fact that the system is receiving something. Unfortunately I am constrained to UDP and not TCP, so need a way to show there is some connection alive (basically that the remote program sending the UDP Packets is running). For context, I am trying to read the contents of a system for displaying a flightplan in an aircraft in a flight simulator. The page should update regularly
The below code doesn't throw errors, but I note in the Console Window even though I attempt to clear the data ready for the next message, I constantly seem to get the same data without updating. I clear the array yet the same data is deposited into it! It is definitely changing in the UDP packets, just not in my code. I restart the app and the page updates, so something isn't clearing right. See below code:
while (runTolissCapt_Connect) //Keep checking for UDP Incoming
{
IPAddress servIPAddress = IPAddress.Parse(TolissIP);
var servEndPoint = new IPEndPoint(servIPAddress, TolissPort_Capt);
if (_TolissCaptUdpClient == null) //If we haven't setup the UdpClient yet
{
lbl_Toliss_Conn.Invoke((MethodInvoker)(() => lbl_Toliss_Conn.ForeColor = Color.DarkRed));
try
{
_TolissCaptUdpClient = new UdpClient(TolissPort_Capt);
mcdu.SetTolissUpdClient(_TolissCaptUdpClient);
}
catch (Exception)
{
}
}
Byte[] receiveData = _TolissCaptUdpClient.Receive(ref servEndPoint); //Receive data
string returnData = Encoding.ASCII.GetString(receiveData); //Format data
if (returnData != null) //If we got some data
{
Toliss_Alive = true;
Console.WriteLine(returnData); //Write UDP message to console
}
else
{
Toliss_Alive = false;
}
Array.Clear(receiveData, 0, receiveData.Length); //Attempt to clear previous UDP message
returnData = "";
if (Toliss_Alive) //Change UI to reflect UDP status
lbl_Toliss_Conn.Invoke((MethodInvoker)(() => lbl_Toliss_Conn.ForeColor = Color.LimeGreen));
else
lbl_Toliss_Conn.Invoke((MethodInvoker)(() => lbl_Toliss_Conn.ForeColor = Color.DarkRed));
new ManualResetEvent(false).WaitOne(500);
}
It is probably simple. Any thoughts are appreciated.