C# 使用udp组播接收消息
时间: 2024-11-20 20:38:14 浏览: 21
在C#中,UDP (用户数据报协议) 组播主要用于接收由单个发送者发送到特定组地址的消息。以下是使用C#创建一个基本的UDP组播接收程序的步骤:
1. 首先,需要添加System.Net.MulticastSocket命名空间,它是处理组播通信的基础。
```csharp
using System.Net;
using System.Net.Sockets;
```
2. 创建MulticastSocket实例,并加入到特定的组播群组:
```csharp
int port = 4567; // 设置接收端口
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("224.0.0.2"), port); // 指定组播IP地址
MulticastGroup group = MulticastGroup.GetGroup(groupEP.Address.ToString()); // 加入组播群组
MulticastSocket socket = new MulticastSocket(AddressFamily.InterNetwork);
socket.JoinMulticastGroup(group);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceivedBufferSize, 65536); // 设置接收缓冲区大小
socket.bind(new IPEndPoint(IPAddress.Any, port)); // 绑定本地IP和端口
```
3. 实现接收逻辑,通过ReceiveAsync方法异步接收消息:
```csharp
byte[] buffer = new byte[65536]; // 接收缓冲区
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); // 用于存储接收到的数据源的远程地址
while (true)
{
IAsyncResult result = socket.ReceiveAsync(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP);
result.AsyncWaitHandle.WaitOne();
if (result.CompletedSynchronously || result.SocketError != SocketError.Success)
{
Console.WriteLine($"Error receiving: {result.SocketError}");
continue;
}
string message = Encoding.UTF8.GetString(buffer, 0, result.BytesReceived);
Console.WriteLine($"Received message from {remoteEP}: {message}");
}
```
阅读全文