12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
-
- 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.UTF8.GetString(data, 0, recv);
- getname.isTrue = false ;
- if (ep.ToString() != null)
- {
- string[] tsIP = ep.ToString().Split(':');
- //getname.AddName(stringData+"_"+tsIP[0]);
- getname.AddName("设备"+"_"+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();
- }
- }
|