当前位置:   article > 正文

Unity接收和发送UDP信号(使用UdpClient)_unity udpclient

unity udpclient
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. using UnityEngine;
  7. public class UDPManager : MonoBehaviour
  8. {
  9. class UDPData
  10. {
  11. private readonly UdpClient udpClient;
  12. public UdpClient UDPClient
  13. {
  14. get { return udpClient; }
  15. }
  16. private readonly IPEndPoint endPoint;
  17. public IPEndPoint EndPoint
  18. {
  19. get { return endPoint; }
  20. }
  21. //构造函数
  22. public UDPData(IPEndPoint endPoint, UdpClient udpClient)
  23. {
  24. this.endPoint = endPoint;
  25. this.udpClient = udpClient;
  26. }
  27. }
  28. string receiveData = string.Empty;
  29. private Action<string> ReceiveCallBack = null;
  30. private Thread RecviveThread;
  31. private void Start()
  32. {
  33. //开启线程
  34. ThreadRecvive();
  35. }
  36. private void Update()
  37. {
  38. if (ReceiveCallBack != null &&
  39. !string.IsNullOrEmpty(receiveData))
  40. {
  41. //调用处理函数去数据进行处理
  42. ReceiveCallBack(receiveData);
  43. //使用之后清空接受的数据
  44. receiveData = string.Empty;
  45. }
  46. }
  47. private void OnDestroy()
  48. {
  49. if (RecviveThread != null)
  50. {
  51. RecviveThread.Abort();
  52. }
  53. }
  54. public void SetReceiveCallBack(Action<string> action)
  55. {
  56. ReceiveCallBack = action;
  57. }
  58. /// <summary>
  59. /// 开始线程接收
  60. /// </summary>
  61. private void ThreadRecvive()
  62. {
  63. //开一个新线程接收UDP发送的数据
  64. RecviveThread = new Thread(() =>
  65. {
  66. //实例化一个IPEndPoint,任意IP和对应端口 端口自行修改
  67. IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 5768);
  68. UdpClient udpReceive = new UdpClient(endPoint);
  69. UDPData data = new UDPData(endPoint, udpReceive);
  70. //开启异步接收
  71. udpReceive.BeginReceive(CallBackRecvive, data);
  72. })
  73. {
  74. //设置为后台线程
  75. IsBackground = true
  76. };
  77. //开启线程
  78. RecviveThread.Start();
  79. }
  80. /// <summary>
  81. /// 异步接收回调
  82. /// </summary>
  83. /// <param name="ar"></param>
  84. private void CallBackRecvive(IAsyncResult ar)
  85. {
  86. try
  87. {
  88. //将传过来的异步结果转为我们需要解析的类型
  89. UDPData state = ar.AsyncState as UDPData;
  90. IPEndPoint ipEndPoint = state.EndPoint;
  91. //结束异步接受 不结束会导致重复挂起线程卡死
  92. byte[] data = state.UDPClient.EndReceive(ar, ref ipEndPoint);
  93. //解析数据 编码自己调整暂定为默认 依客户端传过来的编码而定
  94. receiveData = Encoding.Default.GetString(data);
  95. Debug.Log(receiveData);
  96. //数据的解析再Update里执行 Unity中Thread无法调用主线程的方法
  97. //再次开启异步接收数据
  98. state.UDPClient.BeginReceive(CallBackRecvive, state);
  99. }
  100. catch (Exception e)
  101. {
  102. Debug.LogError(e.Message);
  103. throw;
  104. }
  105. }
  106. /// <summary>
  107. /// 发送UDP信息
  108. /// </summary>
  109. /// <param name="remoteIP">发送地址</param>
  110. /// <param name="remotePort">发送端口</param>
  111. /// <param name="message">需要发送的信息</param>
  112. public void UDPSendMessage(string remoteIP, int remotePort, string message)
  113. {
  114. //将需要发送的内容转为byte数组 编码依接收端为主,自行修改
  115. byte[] sendbytes = Encoding.Unicode.GetBytes(message);
  116. IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort);
  117. UdpClient udpSend = new UdpClient();
  118. //发送数据到对应目标
  119. udpSend.Send(sendbytes, sendbytes.Length, remoteIPEndPoint);
  120. //关闭
  121. udpSend.Close();
  122. }
  123. }

使用UdpClient来接收和发送 注释每一步都有 希望可以看懂,下面是调用的代码

  1. using UnityEngine;
  2. public class NetController : MonoBehaviour
  3. {
  4. void Start()
  5. {
  6. //获取到UDPManager 脚本内部自己开启了线程无需再次开启
  7. UDPManager manager = GetComponent<UDPManager>();
  8. if (manager==null)
  9. {
  10. manager = gameObject.AddComponent<UDPManager>();
  11. }
  12. //设置好解析的方法
  13. manager.SetReceiveCallBack(ReceiveUDPMessage);
  14. }
  15. void ReceiveUDPMessage(string receiveData)
  16. {
  17. //接下来就看自己如何解析了
  18. Debug.Log(receiveData);
  19. }
  20. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/114142?site
推荐阅读
相关标签
  

闽ICP备14008679号