using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json.Linq; using TouchSocket.Core; using TouchSocket.Sockets; using Unity.VisualScripting; using UnityEngine; public class Network : MonoBehaviour { public int Port = 5555; private UdpSession _udpClient; private Dictionary _device1ReadMessages; private Dictionary _device2ReadMessages; private StreamWriter writer; private string _txtPath; void Start() { _txtPath = Application.dataPath + "stream.data"; _device1ReadMessages = new Dictionary(); _device2ReadMessages = new Dictionary(); _udpClient = new UdpSession(); _udpClient.Received += ReceiveMsg; _udpClient.Setup(new TouchSocketConfig() .SetBindIPHost(new IPHost(Port)) .SetUdpDataHandlingAdapter(() => new NormalUdpDataHandlingAdapter())) .Start(); Debug.Log("UDP Client Start!!"); } private void WriteIntoTxt(string message) { FileInfo file = new FileInfo(_txtPath); if (!file.Exists) { writer = file.CreateText(); } else { writer = file.AppendText(); } writer.WriteLine(message); writer.Flush(); writer.Dispose(); writer.Close(); } private void ReceiveMsg(EndPoint endpoint, ByteBlock byteblock, IRequestInfo requestinfo) { string msg = Encoding.UTF8.GetString(byteblock.Buffer, 0, byteblock.Len); //Debug.Log(msg); //WriteIntoTxt(msg); JObject obj = JObject.Parse(msg); JToken token = obj.GetValue("Device1_"+Port); JArray array = token["Parameter"] as JArray; for (int i = 0; i < array.Count; i++) { JObject obj1 = array[i] as JObject; string key = obj1.GetValue("Name").ToString(); string value = obj1.GetValue("Value").ToString(); _device1ReadMessages.AddOrUpdate(key, value); } JToken token2 = obj.GetValue("Device2_"+Port); JArray array2 = token2["Parameter"] as JArray; for (int i = 0; i < array.Count; i++) { JObject obj1 = array2[i] as JObject; string key = obj1.GetValue("Name").ToString(); string value = obj1.GetValue("Value").ToString(); _device2ReadMessages.AddOrUpdate(key, value); } } // Update is called once per frame void Update() { } public float Convert2Angle(int index,string key) { float angle = 0; if (index ==1) { if (!_device1ReadMessages.ContainsKey(key)) { return 0; } string str = _device1ReadMessages[key]; if (!string.IsNullOrEmpty(str)) { angle = Single.Parse(str); } } if (index == 2) { if (!_device2ReadMessages.ContainsKey(key)) { return 0; } string str = _device2ReadMessages[key]; if (!string.IsNullOrEmpty(str)) { angle = Single.Parse(str); } } return angle; } private void OnDestroy() { _udpClient.Received -= ReceiveMsg; _udpClient.Stop(); _udpClient.Dispose(); } }