客户端:

  1. public class UdpClientManager
  2. {
  3. //接收数据事件
  4. public Action<string> recvMessageEvent = null;
  5. //发送结果事件
  6. public Action<int> sendResultEvent = null;
  7. //本地监听端口
  8. public int localPort = 0;
  9.  
  10. private UdpClient udpClient = null;
  11.  
  12. public UdpClientManager(int localPort)
  13. {
  14. if (localPort < 0 || localPort > 65535)
  15. throw new ArgumentOutOfRangeException("localPort is out of range");
  16.  
  17. this.localPort = localPort;
  18. }
  19.  
  20. public void Start()
  21. {
  22. while (true)
  23. {
  24. try
  25. {
  26. udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);//指定本地监听port
  27. ReceiveMessage();
  28. break;
  29. }
  30. catch (Exception)
  31. {
  32. Thread.Sleep(100);
  33. }
  34. }
  35. }
  36.  
  37. private async void ReceiveMessage()
  38. {
  39. while (true)
  40. {
  41. if (udpClient == null)
  42. return;
  43.  
  44. try
  45. {
  46. UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
  47. string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
  48. if (recvMessageEvent != null)
  49. recvMessageEvent(message);
  50. }
  51. catch (Exception ex)
  52. {
  53. }
  54. }
  55. }
  56.  
  57. //单播
  58. public async void SendMessageByUnicast(string message, string destHost, int destPort)
  59. {
  60. if (string.IsNullOrEmpty(message))
  61. throw new ArgumentNullException("message cant not null");
  62. if (udpClient == null)
  63. throw new ArgumentNullException("udpClient cant not null");
  64. if (string.IsNullOrEmpty(destHost))
  65. throw new ArgumentNullException("destHost cant not null");
  66. if (destPort < 0 || destPort > 65535)
  67. throw new ArgumentOutOfRangeException("destPort is out of range");
  68.  
  69. byte[] buffer = Encoding.UTF8.GetBytes(message);
  70. int len = 0;
  71. for (int i = 0; i < 3; i++)
  72. {
  73. try
  74. {
  75. len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(destHost), destPort));
  76. }
  77. catch (Exception)
  78. {
  79. len = 0;
  80. }
  81.  
  82. if (len <= 0)
  83. Thread.Sleep(100);
  84. else
  85. break;
  86. }
  87.  
  88. if (sendResultEvent != null)
  89. sendResultEvent(len);
  90. }
  91.  
  92. public void CloseUdpCliend()
  93. {
  94. if (udpClient == null)
  95. throw new ArgumentNullException("udpClient cant not null");
  96.  
  97. try
  98. {
  99. udpClient.Client.Shutdown(SocketShutdown.Both);
  100. }
  101. catch (Exception)
  102. {
  103. }
  104. udpClient.Close();
  105. udpClient = null;
  106. }
  107. }

  

  

服务器:

  1. public class UdpServiceManager
  2. {
  3. private readonly string broadCastHost = "255.255.255.255";
  4. //接收数据事件
  5. public Action<string> recvMessageEvent = null;
  6. //发送结果事件
  7. public Action<int> sendResultEvent = null;
  8. //本地host
  9. private string localHost = "";
  10. //本地port
  11. private int localPort = 0;
  12.  
  13. private UdpClient udpClient = null;
  14.  
  15. public UdpServiceManager(string localHost, int localPort)
  16. {
  17. if (string.IsNullOrEmpty(localHost))
  18. throw new ArgumentNullException("localHost cant not null");
  19. if (localPort < 0 || localPort > 65535)
  20. throw new ArgumentOutOfRangeException("localPort is out of range");
  21.  
  22. this.localHost = localHost;
  23. this.localPort = localPort;
  24. }
  25.  
  26. public void Start()
  27. {
  28. while (true)
  29. {
  30. try
  31. {
  32. udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(localHost), localPort));//绑定本地host和port
  33. ReceiveMessage();
  34. break;
  35. }
  36. catch (Exception)
  37. {
  38. Thread.Sleep(100);
  39. }
  40. }
  41. }
  42.  
  43. private async void ReceiveMessage()
  44. {
  45. while (true)
  46. {
  47. if (udpClient == null)
  48. return;
  49.  
  50. try
  51. {
  52. UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
  53. string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
  54. if (recvMessageEvent != null)
  55. recvMessageEvent(message);
  56. }
  57. catch (Exception)
  58. {
  59. }
  60. }
  61. }
  62.  
  63. //单播
  64. public async void SendMessageByUnicast(string message, string destHost, int destPort)
  65. {
  66. if (string.IsNullOrEmpty(message))
  67. throw new ArgumentNullException("message cant not null");
  68. if (string.IsNullOrEmpty(destHost))
  69. throw new ArgumentNullException("destHost cant not null");
  70. if (destPort < 0 || destPort > 65535)
  71. throw new ArgumentOutOfRangeException("destPort is out of range");
  72. if (udpClient == null)
  73. throw new ArgumentNullException("udpClient cant not null");
  74.  
  75. byte[] buffer = Encoding.UTF8.GetBytes(message);
  76. int len = 0;
  77. for (int i = 0; i < 3; i++)
  78. {
  79. try
  80. {
  81. len = await udpClient.SendAsync(buffer, buffer.Length, destHost, destPort);
  82. }
  83. catch (Exception)
  84. {
  85. len = 0;
  86. }
  87.  
  88. if (len <= 0)
  89. Thread.Sleep(100);
  90. else
  91. break;
  92. }
  93.  
  94. if (sendResultEvent != null)
  95. sendResultEvent(len);
  96. }
  97.  
  98. //广播
  99. public async void SendMessageByBroadcast(string message)
  100. {
  101. if (string.IsNullOrEmpty(message))
  102. throw new ArgumentNullException("message cant not null");
  103. if (udpClient == null)
  104. throw new ArgumentNullException("udpClient cant not null");
  105.  
  106. byte[] buffer = Encoding.UTF8.GetBytes(message);
  107. int len = 0;
  108. for (int i = 0; i < 3; i++)
  109. {
  110. try
  111. {
  112. len = await udpClient.SendAsync(buffer, buffer.Length, broadCastHost, localPort);
  113. }
  114. catch (Exception ex)
  115. {
  116. len = 0;
  117. }
  118.  
  119. if (len <= 0)
  120. Thread.Sleep(100);
  121. else
  122. break;
  123. }
  124.  
  125. if (sendResultEvent != null)
  126. sendResultEvent(len);
  127. }
  128.  
  129. public void CloseUdpCliend()
  130. {
  131. if (udpClient == null)
  132. throw new ArgumentNullException("udpClient cant not null");
  133.  
  134. try
  135. {
  136. udpClient.Client.Shutdown(SocketShutdown.Both);
  137. }
  138. catch (Exception)
  139. {
  140. }
  141. udpClient.Close();
  142. udpClient = null;
  143. }
  144. }

  

多播方式

  1. public class UdpClientManager
  2. {
  3. //接收数据事件
  4. public Action<string> recvMessageEvent = null;
  5. //发送结果事件
  6. public Action<int> sendResultEvent = null;
  7. //本地监听端口
  8. public int localPort = 0;
  9. //组播地址
  10. public string MultiCastHost = "";
  11.  
  12. private UdpClient udpClient = null;
  13.  
  14. public UdpClientManager(int localPort, string MultiCastHost)
  15. {
  16. if (localPort < 0 || localPort > 65535)
  17. throw new ArgumentOutOfRangeException("localPort is out of range");
  18. if (string.IsNullOrEmpty(MultiCastHost))
  19. throw new ArgumentNullException("message cant not null");
  20.  
  21. this.localPort = localPort;
  22. this.MultiCastHost = MultiCastHost;
  23. }
  24.  
  25. public void Start()
  26. {
  27. while (true)
  28. {
  29. try
  30. {
  31. udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);//指定本地监听port
  32. udpClient.JoinMulticastGroup(IPAddress.Parse(MultiCastHost));
  33. ReceiveMessage();
  34. break;
  35. }
  36. catch (Exception)
  37. {
  38. Thread.Sleep(100);
  39. }
  40. }
  41. }
  42.  
  43. private async void ReceiveMessage()
  44. {
  45. while (true)
  46. {
  47. if (udpClient == null)
  48. return;
  49.  
  50. try
  51. {
  52. UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
  53. string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
  54. if (recvMessageEvent != null)
  55. recvMessageEvent(message);
  56. }
  57. catch (Exception ex)
  58. {
  59. }
  60. }
  61. }
  62.  
  63. public async void SendMessageByMulticast(string message)
  64. {
  65. if (string.IsNullOrEmpty(message))
  66. throw new ArgumentNullException("message cant not null");
  67. if (udpClient == null)
  68. throw new ArgumentNullException("udpClient cant not null");
  69.  
  70. byte[] buffer = Encoding.UTF8.GetBytes(message);
  71. int len = 0;
  72. for (int i = 0; i < 3; i++)
  73. {
  74. try
  75. {
  76. len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(MultiCastHost), localPort));
  77. }
  78. catch (Exception)
  79. {
  80. len = 0;
  81. }
  82.  
  83. if (len <= 0)
  84. Thread.Sleep(100);
  85. else
  86. break;
  87. }
  88.  
  89. if (sendResultEvent != null)
  90. sendResultEvent(len);
  91. }
  92.  
  93. public void CloseUdpCliend()
  94. {
  95. if (udpClient == null)
  96. throw new ArgumentNullException("udpClient cant not null");
  97.  
  98. try
  99. {
  100. udpClient.Client.Shutdown(SocketShutdown.Both);
  101. }
  102. catch (Exception)
  103. {
  104. }
  105. udpClient.Close();
  106. udpClient = null;
  107. }
  108. }

  

C# UdpClient使用的更多相关文章

  1. C# UdpClient使用Receive和BeginReceive接收消息时的不同写法

    使用Receive(同步阻塞方式), 注意使用同步方法时,需要使用线程来开始方法,不然会使UI界面卡死 IPEndPoint RemoteIpEndPoint = ); UdpClient udpCl ...

  2. UDPClient的用法

    UDP_Server: UdpClient receivingUdpClient = ); IPEndPoint RemoteIpEndPoint = ); try { byte[] sdata = ...

  3. Socket的三个功能类TCPClient、TCPListener 和 UDPClient (转)

    应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...

  4. C#使用 UdpClient 类进行简单通信的例子

    UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报. 因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接.但您可以选择使用下面两 ...

  5. C# UdpClient 设置超时时间

    /********************************************************************** * C# UdpClient 设置超时时间 * 说明: ...

  6. UdpClient的Connect究竟做了什么(转)

    最近在写一个音频通信的系统,因为需要还要处理其他事件,所以就自己设计底层的通信协议,用了不少底层的Socket编程(.Net Framework),搞清楚了不少细节问题. 先做一些铺垫工作.音频系统服 ...

  7. 【socket】一分钟理清 socket udpsocket tcpsocket tcplistener TCPClient和 UDPClient

    socket 套接字接口是各种语言tcp udp的网络操作的基础. 直接用socket 对象开发 可以选择 udpsocket  或者 tcpsocket ,两者在使用上仅一些方法和参数不同,所有的底 ...

  8. 【socket】Socket的三个功能类TCPClient、TCPListener 和 UDPClient

    Socket的三个功能类TCPClient.TCPListener 和 UDPClient (转) 应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制 ...

  9. uip UDPclient模式通信移植,当地port随机

    现在移植UDPclient模式,测试广播地址. //udp_client.c /************************************************************ ...

  10. uip UDPclient模式通信移植,p本地ort可以是无规

    现在移植UDPclient模式,使用广播地址检测. //udp_client.c /********************************************************** ...

随机推荐

  1. TMS320C6455小介绍

    TMS320C6455是TI公司推出的的一款新型高性能单核定点DSP.它是TI公司基于第三代先进VeloviTI VLIW(超长指令字)结构开发出来的新产品,在通信,医疗图像,无线传输方面都可以大有作 ...

  2. Spring分层次建包

    1.包分三层 配置包 控制器包 模型包 视图层 模板放 src/main/resources下的templates目录下

  3. [转帖]四个修改Docker默认存储位置的方法

    四个修改Docker默认存储位置的方法 https://blog.51cto.com/forangela/1949947 易改乾坤关注0人评论27435人阅读2017-07-22 09:18:48   ...

  4. js中实现输入框类似百度搜索的智能提示效果

    说明:我这里显示的数据采用词典(词典在js中自定义的,看下面文字),主要显示key. 页面元素: <style type="text/css">.search { le ...

  5. mysql8.0.13下载与安装图文教程

    一.进入mysql网站:https://dev.mysql.com/downloads/mysql/ 二.进入Community选择MySQL Communtiy Server 三.将页面拉到最下面选 ...

  6. Let's Code

    Let's Code Happy Coding, Happy OI #include <bits/stdc++.h> using namespace std; int main() { c ...

  7. 用python库openpyxl操作excel,从源excel表中提取信息复制到目标excel表中

    现代生活中,我们很难不与excel表打交道,excel表有着易学易用的优点,只是当表中数据量很大,我们又需要从其他表册中复制粘贴一些数据(比如身份证号)的时候,我们会越来越倦怠,毕竟我们不是机器,没法 ...

  8. 洛谷P1087 FBI树

    P1087 FBI树题解: 看到这个题,我想到了线段树!(毕竟刚搞完st表...) 当然,题解中有位大佬也用的线段树,但是当时看的时候我看见了9个if,当场去世. 那么这是一个不用暴力的线段树,且简单 ...

  9. 【hash表】收集雪花

    [哈希和哈希表]收集雪花 题目描述 不同的雪花往往有不同的形状.在北方的同学想将雪花收集起来,作为礼物送给在南方的同学们.一共有n个时刻,给出每个时刻下落雪花的形状,用不同的整数表示不同的形状.在收集 ...

  10. 指针生成网络(Pointer-Generator-Network)原理与实战

    指针生成网络(Pointer-Generator-Network)原理与实战   阅读目录 0 前言 1 Baseline sequence-to-sequence 2 Pointer-Generat ...