UDPClientProvider.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using IFramework.Net;
  2. using IFramework.Net.Udp;
  3. using Rokid.MRC;
  4. using System;
  5. using System.Collections;
  6. using System.Text;
  7. using UnityEngine;
  8. namespace IFramework.Custom
  9. {
  10. //客户端连接
  11. public class UDPClientProvider : MonoBehaviour
  12. {
  13. private IUdpClientProvider clientProvider;
  14. private bool isConnect = false;
  15. public int port = 16898;
  16. private string lastIP = "127.0.0.1";
  17. private bool receivedMsg;
  18. private float receivedTime;
  19. private float curTime;
  20. private float heartBeatInterval = 5;
  21. private float reconnectInterval = 3;
  22. private float sendMsgInterval = 2;
  23. private void Awake()
  24. {
  25. Init(ClientCallback);
  26. StartCoroutine(TryConnect());
  27. StartCoroutine(CheckSendIP());
  28. }
  29. //初始化客户端
  30. private void Init( Action<SegmentToken> ReceiveCallback = null)
  31. {
  32. clientProvider = NetTool.CreateUdpClient(4096, 4);
  33. clientProvider.ReceivedOffsetHandler = new OnReceivedSegmentHandler((SegmentToken session) =>
  34. {
  35. ReceiveCallback?.Invoke(session);
  36. });
  37. }
  38. private IEnumerator CheckSendIP()
  39. {
  40. yield return new WaitForSeconds(sendMsgInterval);
  41. if(clientProvider != null)
  42. {
  43. Send(SystemInfo.deviceName);
  44. }
  45. StartCoroutine(CheckSendIP());
  46. //if(!receivedServerMsg)
  47. //{
  48. //}
  49. }
  50. private void Connect(int port)
  51. {
  52. //clientProvider.Disconnect();
  53. string curIP = SDKManager.Instance.GetConnectedDeviceIP();
  54. //todo,检查是否已经连接,目前有问题。可以先移除,不管报错
  55. //if(CheckConnected() && curIP == lastIP)
  56. //{
  57. // return;
  58. //}
  59. //try
  60. //{
  61. // clientProvider.Connect(port, curIP);
  62. //}
  63. //catch(Exception)
  64. //{
  65. //}
  66. clientProvider.Connect(port, curIP);
  67. receivedMsg = false;
  68. lastIP = curIP;
  69. isConnect = true;
  70. //Debug.LogError($"Trying Connecting To Server {lastIP} : {port}");
  71. }
  72. private IEnumerator TryConnect()
  73. {
  74. //yield return new WaitWhile(() =>
  75. //{
  76. // return true;
  77. //});
  78. Connect(port);
  79. yield return new WaitForSeconds(reconnectInterval);
  80. if(!receivedMsg)
  81. {
  82. StartCoroutine(TryConnect());
  83. }
  84. else
  85. {
  86. //收到消息了,开启心跳超时检查
  87. StartCoroutine(HeartBeat());
  88. }
  89. }
  90. private IEnumerator HeartBeat()
  91. {
  92. yield return new WaitUntil(() =>
  93. {
  94. if(!receivedMsg || (receivedMsg && (curTime - receivedTime) > heartBeatInterval))
  95. {
  96. //超时了,重连一下
  97. return true;
  98. }
  99. return false;
  100. });
  101. StartCoroutine(TryConnect());
  102. }
  103. private void ClientCallback(SegmentToken session)
  104. {
  105. string msg = Encoding.UTF8.GetString(session.Data.buffer, session.Data.offset, session.Data.size);
  106. //Debug.LogError("Client Received Msg :" + msg);
  107. if(msg == "OK")
  108. {
  109. receivedMsg = true;
  110. receivedTime = curTime;
  111. }
  112. }
  113. //检查是否连接着。目前测试结果,一旦连接后,即使服务端关闭了,也会一直返回true
  114. private bool CheckConnected()
  115. {
  116. UdpClientProvider provider = (UdpClientProvider)clientProvider;
  117. if(provider == null || provider.socket == null)
  118. {
  119. return false;
  120. }
  121. bool connected = provider.socket.Connected;
  122. Debug.Log($"Socket Connected : {connected}");
  123. return connected;
  124. }
  125. public void SendMsgTest(string msg)
  126. {
  127. //DataFromSDK data = GetHDMPoseData();
  128. //data.timestamp = GetTimeStampSecond();
  129. //data.virtualkey = virtualkey;
  130. //data.hand_points = null;
  131. //string json = JsonUtil.Serialize(data);
  132. //string json = JsonUtility.ToJson(msg);
  133. Send(msg);
  134. }
  135. public void Send(string message)
  136. {
  137. if(isConnect)
  138. {
  139. //Debug.LogError($"Client Send Msg :{message}");
  140. clientProvider.Send(new SegmentOffset(Encoding.UTF8.GetBytes(message)));
  141. }
  142. else
  143. {
  144. Debug.LogWarning("未连接");
  145. }
  146. }
  147. private void Update()
  148. {
  149. curTime = Time.realtimeSinceStartup;
  150. }
  151. private void OnDestroy()
  152. {
  153. Dispose();
  154. }
  155. public void Dispose()
  156. {
  157. clientProvider?.Dispose();
  158. clientProvider = null;
  159. receivedMsg = false;
  160. }
  161. //当跳出设置Wifi后(连接到热点),重新连接
  162. public void OnApplicationPause(bool pause)
  163. {
  164. if(!pause)
  165. {
  166. //Connect(port);
  167. }
  168. }
  169. }
  170. }