UdpClient接收广播地址 [英] UdpClient receive on broadcast address

查看:855
本文介绍了UdpClient接收广播地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中我使用UdpClient.Receive功能:

In c# I am using the UdpClient.Receive function:

public void StartUdpListener(Object state)
    {
        try
        {
            udpServer = new UdpClient(new IPEndPoint(IPAddress.Broadcast, 1234));
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.ErrorCode.ToString());
        }

        IPEndPoint remoteEndPoint = null;
        receivedNotification=udpServer.Receive(ref remoteEndPoint);
        ...



不过我得到一个插座例外称该地址不可用错误代码10049
我该怎么办否定这个异常?

However I am getting a socket exception saying that the address is not available with error code 10049 What do I do to negate this exception?

推荐答案

下面是一些代码,我是JIST目前使用在生产应用程序,工作(我们已经有了一些额外的在那里来处理在客户端服务器是应用程序都在一个独立的安装运行的情况下)。它的任务是接收UDP通知的消息已准备好进行处理。正如亚当·亚历山大提到你唯一的问题是,你需要使用IPAddress.Any,而不是IPAddress.Broadcast。你只用IPAddress.Broadcast当你想要的发送的广播UDP数据包。

Here's the jist of some code I am currently using in a production app that works (we've got a bit extra in there to handle the case where the client are server apps are running on a standalone installation). It's job is to receive udp notifications that messages are ready for processing. As mentioned by Adam Alexander your only problem is that you need to use IPAddress.Any, instead of IPAddress.Broadcast. You would only use IPAddress.Broadcast when you wanted to Send a broadcast UDP packet.

设置UDP客户端

this.broadcastAddress = new IPEndPoint(IPAddress.Any, 1234);
this.udpClient = new UdpClient();
this.udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.udpClient.ExclusiveAddressUse = false; // only if you want to send/receive on same machine.

和触发接收使用回调异步的开始。

And to trigger the start of an async receive using a callback.

this.udpClient.Client.Bind(this.broadcastAddress);
this.udpClient.BeginReceive(new AsyncCallback(this.ReceiveCallback), null);



希望这会有所帮助,你应该能够使其适应工作同步没有太多的问题。非常相似,你在做什么。如果你仍然得到错误此然后还有其他事情后,必须使用您要监听的端口。

Hopefully this helps, you should be able to adapt it to working synchronously without too much issue. Very similar to what you are doing. If you're still getting the error after this then something else must be using the port that you are trying to listen on.

所以,以澄清。

IPAddress.Any =用于接收。我想听听对到达的任何IP地址的数据包。
IPAddress.Broadcast =用于发送。我想发送一个数据包的人谁在听。

IPAddress.Any = Used to receive. I want to listen for a packet arriving on any IP Address. IPAddress.Broadcast = Used to send. I want to send a packet to anyone who is listening.

这篇关于UdpClient接收广播地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆