UDPClient.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. using System.Net;
  2. using System.Net.Sockets;
  3. using System.Text;
  4. using System.Threading;
  5. using System;
  6. using UnityEngine;
  7. namespace Rokid.MRC
  8. {
  9. //客户端,接收服务器的广播的IP消息
  10. public class UDPClient
  11. {
  12. private byte[] recvData;
  13. private int recvSize;
  14. private Socket sock;
  15. private Thread thread;
  16. //接收到服务端的IP后,触发
  17. public Action<string> onReceived;
  18. public void Init(bool broadCast)
  19. {
  20. if(broadCast)
  21. {
  22. StartBroadCast();
  23. }
  24. else
  25. {
  26. StartMultiCast();
  27. }
  28. }
  29. public void OnDestroy()
  30. {
  31. StopBroadCast();
  32. StopMultiCast();
  33. }
  34. //获取服务器IP
  35. public void StartBroadCast()
  36. {
  37. Debug.Log("Client BroadCast");
  38. try
  39. {
  40. if(sock != null)
  41. StopBroadCast();
  42. thread = new Thread(() =>
  43. {
  44. sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  45. IPEndPoint iep = new IPEndPoint(IPAddress.Any, Define.UTP_BroadPort);
  46. sock.Bind(iep);
  47. EndPoint ep = (EndPoint)iep;
  48. recvData = new byte[1024];
  49. Debug.Log(sock.EnableBroadcast);
  50. sock.EnableBroadcast = true;
  51. while(true)
  52. {
  53. recvSize = sock.ReceiveFrom(recvData, ref ep);
  54. string ip = ep.ToString().Split(':')[0];
  55. Debug.Log("Client BroadCast : Server IPEndPoint " + ep.ToString());
  56. Debug.Log("Client BroadCast : Server IP " + ip);
  57. //解析收到的数据,一串服务端的IP地址,未做粘包、拆包处理
  58. string str = Encoding.ASCII.GetString(recvData, 0, recvSize);
  59. if(onReceived != null)
  60. onReceived(ip);
  61. Debug.Log("Client BroadCast : Received " + str);
  62. }
  63. });
  64. thread.Start();
  65. }
  66. catch(Exception e)
  67. {
  68. Debug.LogError("Client BroadCast StartListen Error :" + e.Message);
  69. }
  70. }
  71. //关闭服务器
  72. public void StopBroadCast()
  73. {
  74. if(sock != null)
  75. {
  76. sock.Close();
  77. sock = null;
  78. }
  79. recvData = null;
  80. if(thread != null)
  81. {
  82. thread.Abort();
  83. }
  84. }
  85. //定义一个bool变量,标识是否接收数据
  86. private bool flag = true;
  87. private Thread multiThread;
  88. private UdpClient multiUdp;
  89. private IPAddress addr;
  90. private void StartMultiCast()
  91. {
  92. Debug.Log("Client MultiCast");
  93. //使用端口号实例化UDP连接对象
  94. multiUdp = new UdpClient(Define.UDP_MultiClientPort);
  95. addr = IPAddress.Parse(Define.UDP_MultiCastIP);
  96. multiUdp.JoinMulticastGroup(addr);
  97. //创建IPEndPoint对象,用来显示响应主机的标识
  98. IPEndPoint ipendpoint = new IPEndPoint(addr, Define.UDP_MultiServerPort);
  99. flag = true;
  100. multiThread = new Thread(() =>
  101. {
  102. while(flag)
  103. {
  104. try
  105. {
  106. //判断是否有网络数据
  107. if(multiUdp.Available <= 0)
  108. continue;
  109. if(multiUdp.Client == null)
  110. return;
  111. //从远程主机返回的UDP数据报
  112. byte[] bytes = multiUdp.Receive(ref ipendpoint);
  113. string ip = ipendpoint.ToString().Split(':')[0];
  114. Debug.Log("Client MultiCast : Server IPEndPoint " + ipendpoint.ToString());
  115. Debug.Log("Client MultiCast : Server IP " + ip);
  116. //将获得的UDP数据报转换为字符串形式
  117. string str = Encoding.Default.GetString(bytes);
  118. if(onReceived != null)
  119. onReceived(ip);
  120. Debug.Log("Client MultiCast : Received " + str);
  121. }
  122. catch(Exception ex)
  123. {
  124. Debug.Log(ex.Message);
  125. }
  126. Thread.Sleep(2000);
  127. }
  128. StopMultiCast();
  129. });
  130. multiThread.Start();//启动线程
  131. }
  132. private void StopMultiCast()
  133. {
  134. //不接收数据
  135. flag = false;
  136. if(multiThread != null)
  137. {
  138. if(multiThread.ThreadState == ThreadState.Running)
  139. multiThread.Abort();
  140. }
  141. //if(addr != null)
  142. //{
  143. // multiUdp?.DropMulticastGroup(addr);
  144. // addr = null;
  145. //}
  146. multiUdp?.Close();
  147. }
  148. }
  149. }