using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine; public class UdpClient : MonoBehaviour { private static Socket sock; private static IPEndPoint iep1; private static byte[] data; private Thread t; public EndPoint ep; public GetIPAndLogin getname; string Error_Message; public int udpPort = 9050; void Awake() { GetSeverIP(); } void GetSeverIP() { try { t = new Thread(Receive); t.Start(); } catch (Exception e) { Debug.LogError("错误信息:" + e.Message); } } void Receive() { sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, udpPort); sock.Bind(iep); ep = (EndPoint)iep; while (true) { byte[] data = new byte[1024]; getname.isTrue = true; getname.Cleartemp(); int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); getname.isTrue = false ; if (ep.ToString() != null) { string[] tsIP = ep.ToString().Split(':'); getname.AddName(stringData+"_"+tsIP[0]); } Debug.Log(String.Format("received: {0} from: {1}", stringData, ep.ToString())); Thread.Sleep(2000); } // sock.Close(); } private void OnDestroy() { t = null; sock.Close(); } }