Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# udp

作者:以往沧海   发布日期:2026-04-25   浏览:72

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("已发送响应消息.");
        }
    }
}

解释说明:

  1. UdpClient 类:用于发送和接收 UDP 数据报。这里我们创建了一个 UdpClient 实例,并指定了本地端口号 12345
  2. Receive 方法:阻塞当前线程,直到接收到数据。接收到的数据存储在 byte[] 数组中,同时更新 remoteEndPoint 以包含发送方的 IP 地址和端口号。
  3. Encoding.UTF8.GetString:将接收到的字节数组转换为字符串,以便更方便地处理和显示。
  4. Send 方法:向指定的远程终结点发送响应消息。这里我们将字符串编码为字节数组后发送回去。
  5. using 语句:确保 UdpClient 在使用完毕后自动释放资源。

这个示例展示了如何使用 C# 进行基本的 UDP 通信,包括接收和发送数据。

上一篇:c# 数组初始化

下一篇:c# sm2加密

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站