123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using LitJson;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using Unity.RenderStreaming.Signaling;
- using UnityEngine;
- public class UdpServer : MonoBehaviour
- {
- private static Socket sock;
- private static IPEndPoint iep1;
- private static JsonData data;
- private Thread t;
- string Error_Message;
- public int udpPort = 9050;
- private void Start()
- {
- BroadcastIP();
-
- }
- public void BroadcastIP()
- {
- sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- iep1 = new IPEndPoint(IPAddress.Broadcast, udpPort);
- sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
- t = new Thread(BroadcastMessage);
- t.Start();
- StartCoroutine(getByte());
- }
- IEnumerator getByte()
- {
- while(true)
- {
- data = new JsonData();
- data["p"] = new JsonData();
- data["p"]["x"] = ca.transform.position.x;
- data["p"]["y"] = ca.transform.position.y;
- data["p"]["z"] = ca.transform.position.z;
- data["e"] = new JsonData();
- data["e"]["x"] = ca.transform.position.x;
- data["e"]["y"] = ca.transform.position.y;
- data["e"]["z"] = ca.transform.position.z;
- data["i"] = "";
- yield return new WaitForSeconds(0.03f);
- }
- }
- public Camera ca;
- private void BroadcastMessage()
- {
- while (true)
- {
- if(data!=null)
- {
- sock.SendTo(Encoding.ASCII.GetBytes(data.ToJson()), iep1);
- }
- Thread.Sleep(200);
- }
- }
- private void OnDestroy()
- {
- sock.Close();
- t.Abort();
- }
- }
|