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同一个端口使用的了解。

相关推荐
六点_dn2 分钟前
Linux学习笔记-shell运算符
linux·笔记·学习
其实防守也摸鱼22 分钟前
渗透--损坏的对象级别鉴权漏洞(Broken Object Level Authorization, BOLA)
大数据·网络·数据库·学习·tcp/ip·安全·安全威胁分析
铅笔侠_小龙虾1 小时前
Rust 学习(2)-变量、常量与 shadowing
学习·算法·rust
it小生01011 小时前
从底层思维到高效行动,顶尖人才进阶核心修炼指南
学习·学习方法
逝水无殇1 小时前
C# 特性详解
开发语言·后端·c#
恣逍信点1 小时前
《凌微经》通俗解读——哲学第一因
学习·职场和发展·创业创新·学习方法·业界资讯·交友·哲学
LongtengGensSupreme2 小时前
C#图像内存高速拷贝:使用Marshal.AllocHGlobal与ArrayPool实现内存拷贝的几个方法
开发语言·数码相机·c#
red_redemption2 小时前
自由学习记录(207)
学习
AOwhisky2 小时前
Python 学习笔记(第四期)——字符串:格式化、操作与文本处理——核心知识点自测与详解
开发语言·笔记·python·学习·列表·元组·字典
光学补偿2 小时前
微服务学习 --- Spring Cloud概述
学习·spring cloud·微服务