c# UDP 开发

在C#中使用UDP进行开发,你可以使用System.Net.Sockets命名空间下的UdpClient类。以下是一个简单的UDP发送和接收消息的例子:

UDP发送消息:

复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
public class UdpSend
{
    public static void Main()
    {
        try
        {
            // 创建UdpClient实例
            UdpClient udpClient = new UdpClient();
 
            // 要发送的消息
            string message = "Hello, UDP Server!";
            byte[] data = Encoding.UTF8.GetBytes(message);
 
            // 服务器IP地址和端口
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
 
            // 发送消息
            udpClient.Send(data, data.Length, endPoint);
            Console.WriteLine("Message sent to the server.");
 
            // 关闭UdpClient
            udpClient.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

UDP接收消息:

复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
public class UdpReceive
{
    public static void Main()
    {
        try
        {
            // 创建UdpClient实例,指定监听的端口
            UdpClient udpClient = new UdpClient(11000);
 
            // 接收消息
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = udpClient.Receive(ref RemoteIpEndPoint);
 
            // 解码消息
            string message = Encoding.UTF8.GetString(data);
            Console.WriteLine("Message received: {0}", message);
 
            // 关闭UdpClient
            udpClient.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

在这个例子中,发送方创建了一个UdpClient实例,然后将消息编码并发送到指定的服务器IP地址和端口。接收方同样创建了一个UdpClient实例,监听指定的端口,并在有消息到达时接收和解码消息。

确保在运行这些程序之前,UDP服务器正在监听相应的端口,否则发送方可能会抛出异常。此外,如果你需要处理并发连接或者是大量数据的传输,你可能需要使用异步方法或者调整超时设置等。

相关推荐
神仙别闹1 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
心情好的小球藻21 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己33 分钟前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y40900140 分钟前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
向宇it1 小时前
【unity组件介绍】URP Decal Projector贴花投影器,将特定材质(贴花)投影到场景中的其他对象上。
游戏·3d·unity·c#·游戏引擎·材质
2301_780789665 小时前
UDP和TCP的主要区别是什么
服务器·网络协议·web安全·网络安全·udp
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发6 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++