C# UDP接收字符串
时间: 2024-10-14 19:13:05 浏览: 40
在C#中,要通过UDP(用户数据报协议)接收字符串,你需要创建一个UdpClient实例,并监听指定端口。这里是一个简单的示例,展示了如何在接收到数据后将其解析为字符串:
```csharp
using System.Net;
using System.Net.Sockets;
public class UdpStringReceiver
{
private UdpClient udpClient;
public event EventHandler<UdpReceiveEventArgs> DataReceived;
public UdpStringReceiver(int port)
{
udpClient = new UdpClient(port);
udpClient.DataReceived += OnDataReceived;
}
private void OnDataReceived(object sender, UdpReceiveEventArgs e)
{
byte[] data = e.Buffer;
string receivedString = Encoding.UTF8.GetString(data, 0, data.Length); // 假设数据是以UTF8编码的
if (receivedString != null)
{
DataReceived?.Invoke(this, new UdpReceiveEventArgs(receivedString));
}
}
public async Task StartListening()
{
await udpClient.ReceiveAsync();
}
public void StopListening()
{
udpClient.Close();
}
}
// 使用示例
public static void Main(string[] args)
{
UdpStringReceiver receiver = new UdpStringReceiver(12345);
receiver.DataReceived += (_, e) => Console.WriteLine($"Received string: {e.ReceivedString}");
receiver.StartListening(); // 开始监听
}
```
在这个例子中,我们创建了一个事件处理器`OnDataReceived`,当接收到新的数据时,会从缓冲区解码为字符串并触发`DataReceived`事件。
阅读全文