UdpServer.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Collections;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using UnityEngine;
  7. public class UdpServer : MonoBehaviour
  8. {
  9. public static float resR;
  10. int serverPort = 8085;
  11. int broadcastPort = 8085;
  12. private UdpClient udpServer;
  13. private UdpClient udpBroadcastClient;
  14. private void Start()
  15. {
  16. udpServer = new UdpClient(serverPort);
  17. udpServer.BeginReceive(ReceiveCallback, null);
  18. udpBroadcastClient = new UdpClient();
  19. udpBroadcastClient.EnableBroadcast = true;
  20. Debug.Log("IPAddress.Any+=="+ IPAddress.Any );
  21. //StartCoroutine("sendudp");
  22. }
  23. private void ReceiveCallback(IAsyncResult result)
  24. {
  25. string receivedMessage = "";
  26. try
  27. {
  28. IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, serverPort);
  29. byte[] receivedBytes = udpServer.EndReceive(result, ref clientEndPoint);
  30. receivedMessage = Encoding.ASCII.GetString(receivedBytes);
  31. }
  32. catch (Exception e)
  33. {
  34. Debug.LogError("Error receiving UDP message: " + e.Message);
  35. }
  36. try
  37. {
  38. string[] q1 = receivedMessage.Split(new char[2] { 'R', 'T' });
  39. Debug.Log("收到来自客户端的消息: " + receivedMessage + " q" + q1[1]);
  40. resR = float.Parse(q1[1]);
  41. }
  42. catch (Exception e)
  43. {
  44. Debug.LogError("Error receiving UDP message: " + e.Message);
  45. }
  46. // 继续接收下一个消息
  47. try
  48. {
  49. udpServer.BeginReceive(ReceiveCallback, null);
  50. }
  51. catch (Exception e)
  52. {
  53. Debug.LogError("Error receiving UDP message: " + e.Message);
  54. }
  55. }
  56. public void SendBroadcastMessage(string message)
  57. {
  58. Debug.Log("IPAddress.Broadcast===>"+ IPAddress.Broadcast);
  59. IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), broadcastPort);
  60. byte[] messageBytes = Encoding.ASCII.GetBytes(message);
  61. udpBroadcastClient.Send(messageBytes, messageBytes.Length, broadcastEndPoint);
  62. }
  63. private void OnDestroy()
  64. {
  65. if (udpServer != null)
  66. {
  67. udpServer.Close();
  68. }
  69. if (udpBroadcastClient != null)
  70. {
  71. udpBroadcastClient.Close();
  72. }
  73. }
  74. IEnumerator sendudp()
  75. {
  76. yield return null;
  77. while (true)
  78. {
  79. Debug.Log("发送hello");
  80. SendBroadcastMessage("hello client!");
  81. yield return null;
  82. }
  83. }
  84. private void Update()
  85. {
  86. if (Input.GetKeyDown(KeyCode.K))
  87. {
  88. Debug.Log("发送");
  89. SendBroadcastMessage("hello client!");
  90. }
  91. }
  92. }