using UnityEngine; using QFramework; using System; using System.Text; using System.Net.Sockets; using System.Threading; using System.Net; public class UDPUtility : IUtility { public string udpAddress; public int udpPort; public UdpClient udpClient; public NetworkStream sendStream; public BindableProperty isOpenUDP = new BindableProperty(false); public bool isReceivedValue = false; public BindableProperty receivedData = new BindableProperty(""); public BindableProperty exceptionData = new BindableProperty(""); public Thread reciveT; public BindableProperty isTimeOut = new BindableProperty(false); public UDPUtility() { Debug.LogWarning("使用无参数构造udp时,需要手动开启udp服务"); } public UDPUtility(string UDPAddress, int UDPPort) { this.udpAddress = UDPAddress; this.udpPort = UDPPort; StartUDPClient(UDPAddress, UDPPort); } public bool StartUDPClient(string ip, int port) { isTimeOut.Value = false; if (!isOpenUDP) { udpAddress = ip; udpPort = port; try { udpClient = new UdpClient(udpAddress, udpPort); } catch (Exception e) { exceptionData.Value = e.ToString(); return false; } isOpenUDP.Value = true; reciveT = new Thread(RecciveMsg); reciveT.IsBackground = true; reciveT.Start(); return true; } return false; } public void CloseUDPClient() { udpClient.Dispose(); isOpenUDP.Value = false; reciveT.Abort(); } public void sendData(string data) { if (isOpenUDP == false) return; Byte[] sendBytes = Encoding.Default.GetBytes(data); udpClient.Send(sendBytes, sendBytes.Length); } public void RecciveMsg() { string msg = ""; //Debug.Log("StartReceiving!"); while (isOpenUDP.Value) { try { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); msg = Encoding.UTF8.GetString(receiveBytes); if (msg != "") { receivedData.Value = msg; isReceivedValue = true; } } catch (Exception e) { Debug.LogWarning(e); //断线发送异常 isTimeOut.Value = true; exceptionData.Value = e.ToString(); break; } } Debug.Log("------------end While-------------"); } /// /// 线程接收到消息后 /// /// 接收到的消息 public string getReceivedValue() { if (isReceivedValue) { isReceivedValue = false; return receivedData.Value; } else { return ""; } } public bool getTimeOutState() { return isTimeOut; } public bool IsReceivedMsg() { return sendStream.Length != 0; } public bool IsConnected() { return udpClient.Client.Connected; } }