using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
// 创建一个UdpClient实例,指定本地端口
using (UdpClient udpClient = new UdpClient(12345))
{
IPEndPoint remoteEndPoint = null;
Console.WriteLine("等待接收UDP数据...");
// 接收数据
byte[] receivedBytes = udpClient.Receive(ref remoteEndPoint);
// 将接收到的字节数组转换为字符串
string receivedMessage = Encoding.UTF8.GetString(receivedBytes);
Console.WriteLine($"从 {remoteEndPoint} 收到消息: {receivedMessage}");
// 发送响应
string responseMessage = "Hello, UDP Client!";
byte[] sendBytes = Encoding.UTF8.GetBytes(responseMessage);
udpClient.Send(sendBytes, sendBytes.Length, remoteEndPoint);
Console.WriteLine("已发送响应消息.");
}
}
}
UdpClient 实例,并指定了本地端口号 12345。byte[] 数组中,同时更新 remoteEndPoint 以包含发送方的 IP 地址和端口号。UdpClient 在使用完毕后自动释放资源。这个示例展示了如何使用 C# 进行基本的 UDP 通信,包括接收和发送数据。
上一篇:c# 数组初始化
下一篇:c# sm2加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站