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 在广播地址上接收
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
