C# Application not receiving packets on UDPClient.Receive

最后都变了- 提交于 2019-11-29 12:36:32

UDP is a connection-less protocol. Don't Connect. Instead, you're simply passing packets of data. Also, when you're using UdpClient, don't dig down to the underlying socket. There's no point.

The simplest (and quite stupid) UDP listener would look something like this:

var listener = new UdpClient(54323, AddressFamily.InterNetwork);

var ep = default(IPEndPoint);

while (!done)
{
    var data = listener.Receive(ref ep);

    // Process the data
}

Doing all the stuff around ExclusiveAddressUse (and SocketOptionName.ReuseAddress) only serves to hide problems from you. Unless you're using broadcast or multi-cast, only one of the UDP listeners on that port will get the message. That's usually a bad thing.

If this simple code doesn't work, check the piping. Firewalls, IP addresses, drivers, the like. Install WireShark and check that the UDP packets are actually coming through - it might be the device's fault, it might be wrong configuration.

Also, ideally you'd want to do all this asynchronously. If you've got .NET 4.5, this is actually quite easy.

If you are running this on Windows Vista or beyond, it is probably the UAC. It can quietly prevent sockets from working properly. If you turn the UAC level down, it won't just block the socket.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!