C#学习系列之UDP同端口发送与接收

C#学习系列之UDP同端口发送与接收


啰嗦

项目中需要同一端口的发送与接收,当时一直都没有在同一个程序中对同一个端口进行发送与接收的尝试。

采用的形式是定义两个UdpClient,对同一UDP端口进行收发与接收。结果导致总有一个线程会kill掉,无法使用。


解决方案

同一个端口的接收与发送,还是需要定义两个线程进行读写。

但是不需要同时定义两个UdpClient

当定义好一个UdpClient,直接使用。

代码

csharp 复制代码
UdpClient Client = null;

void RecvThread()
{
    if (Client == null)
    {
        Client = new UdpClient(iDataPort);
        Client.JoinMulticastGroup(IPAddress.Parse(iDataIP));
    }
    IPEndPoint multicast = new IPEndPoint(IPAddress.Parse(iDataIP), iDataPort);
    while (true)
    {
        byte[] buf = Client.Receive(ref multicast);
        Thread.Sleep(40);
    }
}

void SendThread()
{
     IPEndPoint multicast = new IPEndPoint(IPAddress.Parse(iDataIP), iDataPort);
     while (true)
     {
         byte[] buf;
         bool getBl = mySendData.TryDequeue(out buf);
         if (getBl)
         {
             if (buf != null)
             {
                 int isSend = Client.Send(buf, buf.Length, multicast);
             }
         }
         Thread.Sleep(40);
     }
}

这里有两个线程开辟,需要注意在收线程中将Client赋值了,所以发送线程中Client不会为null,所以一定要主要这个问题,否则会报错!


总结

通过实际项目又填补了自己对UDP同一个端口使用的了解。

相关推荐
冬夜戏雪4 小时前
实习面经摘录(九)
学习
arvin_xiaoting4 小时前
OpenClaw学习总结_I_核心架构_8:SessionPruning详解
前端·chrome·学习·系统架构·ai agent·openclaw·sessionpruning
妄汐霜6 小时前
小白学习笔记(spring框架的aop和tx)
笔记·学习
椎4958 小时前
JSONUtil工具包大致学习使用
学习
leiming68 小时前
CAN 通信协议学习讲义(带图文 + C 语言代码)
c语言·开发语言·学习
星空9 小时前
RAG学习第一节
学习
知识分享小能手10 小时前
MongoDB入门学习教程,从入门到精通,MongoDB入门指南 —— 知识点详解(2)
数据库·学习·mongodb
炽烈小老头10 小时前
【 每天学习一点算法 2026/03/24】寻找峰值
学习·算法
Nan_Shu_61410 小时前
学习:Cesium (3)
学习
Du_chong_huan10 小时前
3.2 无连接运输:UDP 协议|《计算机网络:自顶向下方法》精读
网络协议·计算机网络·udp