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服务器正在监听相应的端口,否则发送方可能会抛出异常。此外,如果你需要处理并发连接或者是大量数据的传输,你可能需要使用异步方法或者调整超时设置等。

相关推荐
灰子学技术13 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
二十雨辰14 小时前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码14 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚14 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂14 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
pas13614 小时前
41-parse的实现原理&有限状态机
开发语言·前端·javascript
bugcome_com14 小时前
零基础入门C#:一篇搞懂核心知识点
c#
琹箐14 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
Monly2115 小时前
Java:修改打包配置文件
java·开发语言
我命由我1234515 小时前
Android 广播 - 静态注册与动态注册对广播接收器实例创建的影响
android·java·开发语言·java-ee·android studio·android-studio·android runtime