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

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


啰嗦

项目中需要同一端口的发送与接收,当时一直都没有在同一个程序中对同一个端口进行发送与接收的尝试。
采用的形式是定义两个UdpClient,对同一UDP端口进行收发与接收。结果导致总有一个线程会kill掉,无法使用。


解决方案

同一个端口的接收与发送,还是需要定义两个线程进行读写。
但是不需要同时定义两个UdpClient
当定义好一个UdpClient,直接使用。

代码

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

相关推荐

  1. C#学习系列UDP端口发送接收

    2024-06-11 16:56:02       11 阅读
  2. udp进行数据发送接收

    2024-06-11 16:56:02       35 阅读
  3. QT网络编程实现UDP广播发送接收

    2024-06-11 16:56:02       19 阅读
  4. UDP发送接受数据

    2024-06-11 16:56:02       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-11 16:56:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-11 16:56:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-11 16:56:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-11 16:56:02       20 阅读

热门阅读

  1. Web基础与HTTP协议

    2024-06-11 16:56:02       6 阅读
  2. 第三十篇-Ollama-TeslaP40-Ollama-Qwen2-57B等速度

    2024-06-11 16:56:02       9 阅读
  3. Comparison of manual and robotic cleaning

    2024-06-11 16:56:02       8 阅读
  4. 十种排序方法

    2024-06-11 16:56:02       7 阅读
  5. C#类库打包支持多个版本的类库

    2024-06-11 16:56:02       7 阅读
  6. 嵌入式软件测试相关分析

    2024-06-11 16:56:02       9 阅读