using UnityEngine; using QFrameworkCP; 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 bool isOpenUDP = false; public bool isReceivedValue = false; public string receivedData = ""; public string exceptionData = ""; public Thread reciveT; public bool isTimeOut = 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 = false; if (!isOpenUDP) { udpAddress = ip; udpPort = port; try { udpClient = new UdpClient(udpAddress, udpPort); } catch (Exception e) { exceptionData = e.ToString(); return false; } isOpenUDP = true; reciveT = new Thread(RecciveMsg); reciveT.IsBackground = true; reciveT.Start(); return true; } return false; } public void CloseUDPClient() { udpClient.Dispose(); isOpenUDP = 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) { try { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); msg = Encoding.UTF8.GetString(receiveBytes); if (msg != "") { receivedData = msg; isReceivedValue = true; } } catch (Exception e) { Debug.LogWarning(e); //断线发送异常 isTimeOut = true; exceptionData = e.ToString(); break; } } Debug.Log("------------end While-------------"); } /// /// 线程接收到消息后 /// /// 接收到的消息 public string getReceivedValue() { if (isReceivedValue) { isReceivedValue = false; return receivedData; } else { return ""; } } public bool getTimeOutState() { return isTimeOut; } public bool IsReceivedMsg() { return sendStream.Length != 0; } public bool IsConnected() { return udpClient.Client.Connected; } }