UDPThread.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace ToolsClassLibrary.UDP
  11. {
  12. public class UDPThread
  13. {
  14. #region 私有变量
  15. UdpClient client;//UDP客户端
  16. List<UdpPacket> sendlist;// 用于轮询是否发送成功的记录
  17. Dictionary<long, RecDataList> RecListDic = new Dictionary<long, RecDataList>();//数据接收列表,每一个sequence对应一个
  18. IPEndPoint remotIpEnd = null;//用来在接收数据的时候对远程主机的信息存放
  19. int port = 8787;//定义服务器的端口号
  20. #endregion
  21. #region 属性
  22. public int CheckQueueTimeInterval { get; set; }//检查发送队列间隔
  23. public int MaxResendTimes { get; set; }//没有收到确认包时,最大重新发送的数目,超过此数目会丢弃并触发PackageSendFailture事件
  24. #endregion
  25. #region 事件
  26. /// <summary>
  27. /// 当数据包收到时触发
  28. /// </summary>
  29. public event EventHandler<PackageEventArgs> PackageReceived;
  30. /// <summary>
  31. /// 当数据包收到事件触发时,被调用
  32. /// </summary>
  33. /// <param name="e">包含事件的参数</param>
  34. protected virtual void OnPackageReceived(PackageEventArgs e)
  35. {
  36. if (PackageReceived != null)
  37. PackageReceived(this, e);
  38. }
  39. /// <summary>
  40. /// 数据包发送失败
  41. /// </summary>
  42. public event EventHandler<PackageEventArgs> PackageSendFailure;
  43. /// <summary>
  44. /// 当数据发送失败时调用
  45. /// </summary>
  46. /// <param name="e">包含事件的参数</param>
  47. protected virtual void OnPackageSendFailure(PackageEventArgs e)
  48. {
  49. if (PackageSendFailure != null)
  50. PackageSendFailure(this, e);
  51. }
  52. /// <summary>
  53. /// 数据包未接收到确认,重新发送
  54. /// </summary>
  55. public event EventHandler<PackageEventArgs> PackageResend;
  56. /// <summary>
  57. /// 触发重新发送事件
  58. /// </summary>
  59. /// <param name="e">包含事件的参数</param>
  60. protected virtual void OnPackageResend(PackageEventArgs e)
  61. {
  62. if (PackageResend != null)
  63. PackageResend(this, e);
  64. }
  65. #endregion
  66. //无参构造函数
  67. public UDPThread()
  68. {
  69. }
  70. //构造函数
  71. public UDPThread(string ipaddress, int port)
  72. {
  73. IPAddress ipA = IPAddress.Parse(ipaddress);//构造远程连接的参数
  74. IPEndPoint ipEnd = new IPEndPoint(ipA, port);
  75. client = new UdpClient();// client = new UdpClient(ipEnd)这样的话就没有创建远程连接
  76. client.Connect(ipEnd);//使用指定的远程主机信息建立默认远程主机连接
  77. sendlist = new List<UdpPacket>();
  78. CheckQueueTimeInterval = 2000;//轮询间隔时间
  79. MaxResendTimes = 5;//最大发送次数
  80. new Thread(new ThreadStart(CheckUnConfirmedQueue)) { IsBackground = true }.Start();//启动轮询线程
  81. //开始监听数据
  82. AsyncReceiveData();
  83. }
  84. /// <summary>
  85. /// 同步数据接收方法
  86. /// </summary>
  87. public void ReceiveData()
  88. {
  89. while (true)
  90. {
  91. IPEndPoint retip = null;
  92. UdpPacket udpp = null;
  93. try
  94. {
  95. byte[] data = client.Receive(ref retip);//接收数据,当Client端连接主机的时候,retip就变成Cilent端的IP了
  96. udpp = (UdpPacket)SerializationUnit.DeserializeObject(data);
  97. }
  98. catch (Exception ex)
  99. {
  100. //异常处理操作
  101. }
  102. if (udpp != null)
  103. {
  104. PackageEventArgs arg = new PackageEventArgs(udpp, retip);
  105. OnPackageReceived(arg);//数据包收到触发事件
  106. }
  107. }
  108. }
  109. //异步接受数据
  110. public void AsyncReceiveData()
  111. {
  112. try
  113. {
  114. client.BeginReceive(new AsyncCallback(ReceiveCallback), null);
  115. }
  116. catch (SocketException ex)
  117. {
  118. throw ex;
  119. }
  120. }
  121. //接收数据的回调函数
  122. public void ReceiveCallback(IAsyncResult param)
  123. {
  124. if (param.IsCompleted)
  125. {
  126. UdpPacket udpp = null;
  127. try
  128. {
  129. byte[] data = client.EndReceive(param, ref remotIpEnd);//接收数据,当Client端连接主机的时候,test就变成Cilent端的IP了
  130. udpp = (UdpPacket)SerializationUnit.DeserializeObject(data);
  131. }
  132. catch (Exception ex)
  133. {
  134. //异常处理操作
  135. }
  136. finally
  137. {
  138. AsyncReceiveData();
  139. }
  140. if (udpp != null)//触发数据包收到事件
  141. {
  142. PackageEventArgs arg = new PackageEventArgs(udpp, null);
  143. OnPackageReceived(arg);
  144. }
  145. }
  146. }
  147. /// <summary>
  148. /// 同步发送分包数据
  149. /// </summary>
  150. /// <param name="message"></param>
  151. public void SendData(Msg message)
  152. {
  153. ICollection<UdpPacket> udpPackets = UdpPacketSplitter.Split(message);
  154. foreach (UdpPacket udpPacket in udpPackets)
  155. {
  156. byte[] udpPacketDatagram = SerializationUnit.SerializeObject(udpPacket);
  157. //使用同步发送
  158. client.Send(udpPacketDatagram, udpPacketDatagram.Length, udpPacket.remoteip);
  159. if (udpPacket.IsRequireReceiveCheck)
  160. PushSendItemToList(udpPacket);//将该消息压入列表
  161. }
  162. }
  163. /// <summary>
  164. /// 异步分包发送数组的方法
  165. /// </summary>
  166. /// <param name="message"></param>
  167. public void AsyncSendData(Msg message)
  168. {
  169. ICollection<UdpPacket> udpPackets = UdpPacketSplitter.Split(message);
  170. foreach (UdpPacket udpPacket in udpPackets)
  171. {
  172. byte[] udpPacketDatagram = SerializationUnit.SerializeObject(udpPacket);
  173. //使用同步发送
  174. //client.Send(udpPacketDatagram, udpPacketDatagram.Length);
  175. //使用异步的方法发送数据
  176. this.client.BeginSend(udpPacketDatagram, udpPacketDatagram.Length, new AsyncCallback(SendCallback), null);
  177. }
  178. }
  179. //发送完成后的回调方法
  180. public void SendCallback(IAsyncResult param)
  181. {
  182. if (param.IsCompleted)
  183. {
  184. try
  185. {
  186. client.EndSend(param);//这句话必须得写,BeginSend()和EndSend()是成对出现的
  187. }
  188. catch (Exception e)
  189. {
  190. //其他处理异常的操作
  191. }
  192. }
  193. }
  194. static object lockObj = new object();
  195. /// <summary>
  196. /// 自由线程,检测未发送的数据并发出,存在其中的就是没有收到确认包的数据包
  197. /// </summary>
  198. void CheckUnConfirmedQueue()
  199. {
  200. do
  201. {
  202. if (sendlist.Count > 0)
  203. {
  204. UdpPacket[] array = null;
  205. lock (sendlist)
  206. {
  207. array = sendlist.ToArray();
  208. }
  209. //挨个重新发送并计数
  210. Array.ForEach(array, s =>
  211. {
  212. s.sendtimes++;
  213. if (s.sendtimes >= MaxResendTimes)
  214. {
  215. //sOnPackageSendFailure//出发发送失败事件
  216. sendlist.Remove(s);//移除该包
  217. }
  218. else
  219. {
  220. //重新发送
  221. byte[] udpPacketDatagram = SerializationUnit.SerializeObject(s);
  222. client.Send(udpPacketDatagram, udpPacketDatagram.Length, s.remoteip);
  223. }
  224. });
  225. }
  226. Thread.Sleep(CheckQueueTimeInterval);//间隔一定时间重发数据
  227. } while (true);
  228. }
  229. /// <summary>
  230. /// 将数据信息压入列表
  231. /// </summary>
  232. /// <param name="item"></param>
  233. void PushSendItemToList(UdpPacket item)
  234. {
  235. sendlist.Add(item);
  236. }
  237. /// <summary>
  238. /// 将数据包从列表中移除
  239. /// </summary>
  240. /// <param name="packageNo">数据包编号</param>
  241. /// <param name="packageIndex">数据包分包索引</param>
  242. public void PopSendItemFromList(long packageNo, int packageIndex)
  243. {
  244. lock (lockObj)
  245. {
  246. Array.ForEach(sendlist.Where(s => s.sequence == packageNo && s.index == packageIndex).ToArray(), s => sendlist.Remove(s));
  247. }
  248. }
  249. /// <summary>
  250. /// 关闭客户端并释放资源
  251. /// </summary>
  252. public void Dispose()
  253. {
  254. if (client != null)
  255. {
  256. client.Close();
  257. client = null;
  258. }
  259. }
  260. }
  261. }