C# 如何实现udp通讯 循环中 接到上条回复消息后 再发送指令
时间: 2024-02-23 10:58:42 浏览: 21
在 C# 中,可以使用 UdpClient 类来实现 UDP 通讯。下面是一个示例代码,演示如何在循环中接收到上一条消息后再发送指令:
```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpExample
{
static void Main(string[] args)
{
// 创建一个 UdpClient 对象,绑定本地端口
UdpClient udpClient = new UdpClient(8888);
while (true)
{
// 接收数据
IPEndPoint remoteEP = null;
byte[] receiveBytes = udpClient.Receive(ref remoteEP);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
// 发送数据
string sendString = "Hello";
byte[] sendBytes = Encoding.ASCII.GetBytes(sendString);
udpClient.Send(sendBytes, sendBytes.Length, remoteEP);
// 等待一段时间后再发送下一条消息
System.Threading.Thread.Sleep(1000);
}
}
}
```
在上面的代码中,通过调用 `Receive()` 方法接收数据,并通过 `Send()` 方法发送数据。在接收到上一条消息后,通过 `Thread.Sleep()` 方法等待一段时间后再发送下一条消息。