以下是使用 UDP 协议进行发送和接收数据的 C# 代码示例:

发送端代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UdpSender
{
    static void Main(string[] args)
    {
        // 定义 UDP 发送端口号
        int port = 12345;
        // 定义要发送的数据
        byte[] data = Encoding.UTF8.GetBytes('Hello, UDP!');
        // 定义要发送到的 IP 地址和端口号
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse('192.168.1.100'), port);
        // 创建 UDP 客户端
        UdpClient udpClient = new UdpClient();
        // 发送数据
        udpClient.Send(data, data.Length, remoteEP);
        Console.WriteLine('数据已发送。');
        Console.ReadKey();
    }
}

接收端代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UdpReceiver
{
    static void Main(string[] args)
    {
        // 定义 UDP 接收端口号
        int port = 12345;
        // 创建 UDP 服务器
        UdpClient udpServer = new UdpClient(port);
        // 接收数据
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
        byte[] data = udpServer.Receive(ref remoteEP);
        Console.WriteLine('收到来自 {0} 的数据:{1}', remoteEP.ToString(), Encoding.UTF8.GetString(data));
        Console.ReadKey();
    }
}
C# UDP 发送和接收数据示例代码

原文地址: https://www.cveoy.top/t/topic/oWPM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录