UdpServer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using LitJson;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using Unity.RenderStreaming.Signaling;
  10. using UnityEngine;
  11. public class UdpServer : MonoBehaviour
  12. {
  13. private static Socket sock;
  14. private static IPEndPoint iep1;
  15. private static JsonData data;
  16. private Thread t;
  17. string Error_Message;
  18. public int udpPort = 9050;
  19. private void Start()
  20. {
  21. BroadcastIP();
  22. }
  23. public void BroadcastIP()
  24. {
  25. sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  26. iep1 = new IPEndPoint(IPAddress.Broadcast, udpPort);
  27. sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  28. t = new Thread(BroadcastMessage);
  29. t.Start();
  30. StartCoroutine(getByte());
  31. }
  32. IEnumerator getByte()
  33. {
  34. while(true)
  35. {
  36. data = new JsonData();
  37. data["p"] = new JsonData();
  38. data["p"]["x"] = ca.transform.position.x;
  39. data["p"]["y"] = ca.transform.position.y;
  40. data["p"]["z"] = ca.transform.position.z;
  41. data["e"] = new JsonData();
  42. data["e"]["x"] = ca.transform.position.x;
  43. data["e"]["y"] = ca.transform.position.y;
  44. data["e"]["z"] = ca.transform.position.z;
  45. data["i"] = "";// WebSocketSignaling.m_url;
  46. yield return new WaitForSeconds(0.03f);
  47. }
  48. }
  49. public Camera ca;
  50. private void BroadcastMessage()
  51. {
  52. while (true)
  53. {
  54. if(data!=null)
  55. {
  56. sock.SendTo(Encoding.ASCII.GetBytes(data.ToJson()), iep1);
  57. }
  58. Thread.Sleep(200);
  59. }
  60. }
  61. private void OnDestroy()
  62. {
  63. sock.Close();
  64. t.Abort();
  65. }
  66. }