我有一个程序,通过 UDP 将数据从一台计算机发送到另一台计算机。问题是数据可能并不总是由发送程序发送,我希望仅在将某些内容发送到指定端口(在本例中为 5000)时启用接收程序的接收功能,否则当用户尝试接收数据时在使用程序的端口上UdpClient
崩溃。例如:
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();
}
我的问题是当没有数据发送并且用户单击receiveButton
主窗口时,我的整个程序崩溃了。具体来说,问题在这里:
receive_byte_array = listener.Receive(ref groupEP);
我试图通过将上面的代码行放在 try catch 语句中来解决问题,但即使这样程序也会崩溃!当没有任何数据时,似乎只是试图在 IPEndpoint 端口上接收数据。
关于如何首先检查数据是否正在发送到端口然后才允许用户接收数据的任何想法?提前致谢。