[英]C# Application not receiving packets on UDPClient.Receive
我遇到了一个似乎无法调试的奇怪问题。 我的应用程序收到了来自通过特定端口发送UDP数据包的设备的数据包。 设置UDP侦听器后,while循环会定期触发Receive命令。
我应该在每个给定的时间间隔接收400个值,并且甚至设置一个过程来确保这些值通过。 以下是相关代码的片段:
public UdpClient listener;
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
//where listenPort is an int holding the port values should be received from
listener.ExclusiveAddressUse = false;
listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Client.Bind(groupEP);
if (listener.Client.Connected)
{
listener.Connect(groupEP);
}
//I've actually never seen the app actually enter the code contained above
try
{
while (!done)
{
if (isListenerClosed == false && currentDevice.isConnected)
{
try
{
receive_byte_array = listener.Receive(ref groupEP);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
catch (SocketException ex)
{
throw ex;
}
奇怪的是,该应用程序在我的PC上运行正常(通过安装文件/ Installshield以及在Visual Studio中运行),但是在同事的计算机上运行安装文件时不会接收任何数据(在Windows 2000中运行正常)他的Visual Studio环境)。 我还尝试将Visual Studio附加到应用程序的进程中,在该进程中,我发现代码可以正常运行,直到到达listener.Receive
为止。 没有异常被捕获,VS中没有错误,但是由于没有接收到数据,所以代码只是停止了。
顺便提一句,两台机器都是相同的(运行64位Windows 7 Ultimate N的Mac Mini)。
我甚至在主程序中包括一个UnhandledExceptionHandler,如下所示:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("Unhandled Exception Caught " + e.ToString());
throw new NotImplementedException();
}
这可能是Windows中的“应用程序”权限问题吗? 关于找出问题的最佳方法有什么想法?
UDP是无连接协议。 不要Connect
。 相反,您只是在传递数据包。 另外,当您使用UdpClient
,请不要深入研究基础套接字。 毫无意义。
最简单(也很愚蠢)的UDP侦听器如下所示:
var listener = new UdpClient(54323, AddressFamily.InterNetwork);
var ep = default(IPEndPoint);
while (!done)
{
var data = listener.Receive(ref ep);
// Process the data
}
围绕ExclusiveAddressUse
(和SocketOptionName.ReuseAddress
)进行所有操作只能为您隐藏问题。 除非您使用广播或多播,否则该端口上只有一个UDP侦听器会收到该消息。 这通常是一件坏事。
如果此简单代码不起作用,请检查管道。 防火墙,IP地址,驱动程序等。 安装WireShark并检查UDP数据包是否确实通过-这可能是设备的故障,可能是错误的配置。
另外,理想情况下,您希望异步执行所有这些操作。 如果您有.NET 4.5,这实际上很容易。
如果您在Windows Vista或更高版本上运行此程序 ,则可能是UAC
。 它可以悄悄地阻止套接字正常工作。 如果将UAC
级别调低,它不仅会阻塞套接字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.