I have a program whereby Data is being sent from one computer to another via UDP. The problem is that data may not always be sent by the sending program and I want my receiving program’s receive functionality to be enabled ONLY when something is being sent to a specified port (5000 in this case), otherwise when the user tries to receive data on the port using UdpClient the program crashes. For example:
private const int listenPort = 5000;//receiving port
UdpClient listener = new UdpClient(listenPort);//udclient instance
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
public string received_data;
public byte[] receive_byte_array;
private void receiveButton_Click(object sender, RoutedEventArgs e)
{
receive_byte_array = listener.Receive(ref groupEP);
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
textBox1.Text = received_data.ToString();
}
My problem here is when there is no data being sent and the User clicks receiveButton on the main window my whole program crashes. To be specific the problem is here:
receive_byte_array = listener.Receive(ref groupEP);
I’ve tried to fix the problem by putting the above line of code in a try catch statement but even then the program crashes! It seems merely trying to receive data on the IPEndpoint port when there is none raises hell.
Any ideas as to how I can first check if data is being sent to the port and only then allow the user to receive data? Thanks in advance.
based on your comment I’d say the program is freezing because it is waiting for data to receive. your user interface freezes because you’ve started listening for data synchronously from the UI thread and it is now preoccupied with listening for data and not repainting or processing input. to fix this put the listening bit in a separate thread or use the async BeginReceive method to receive the data.