UdpClient receive on broadcast address(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?
推荐答案
以下是我目前在生产应用程序中使用的一些代码的概要(我们有一些额外的代码来处理客户端是服务器应用程序在独立安装上运行).它的工作是接收消息已准备好处理的 udp 通知.正如亚当亚历山大所提到的,您唯一的问题是您需要使用 IPAddress.Any,而不是 IPAddress.Broadcast.当您想要发送广播 UDP 数据包时,您只会使用 IPAddress.Broadcast.
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 在广播地址上接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UdpClient 在广播地址上接收
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01