UdpClient.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 
  2. using System;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading;
  7. using UnityEngine;
  8. public class UdpClient : MonoBehaviour
  9. {
  10. private static Socket sock;
  11. private static IPEndPoint iep1;
  12. private static byte[] data;
  13. private Thread t;
  14. public EndPoint ep;
  15. public GetIPAndLogin getname;
  16. string Error_Message;
  17. public int udpPort = 9050;
  18. void Awake()
  19. {
  20. GetSeverIP();
  21. }
  22. void GetSeverIP()
  23. {
  24. try
  25. {
  26. t = new Thread(Receive);
  27. t.Start();
  28. }
  29. catch (Exception e)
  30. {
  31. Debug.LogError("错误信息:" + e.Message);
  32. }
  33. }
  34. void Receive()
  35. {
  36. sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  37. IPEndPoint iep = new IPEndPoint(IPAddress.Any, udpPort);
  38. sock.Bind(iep);
  39. ep = (EndPoint)iep;
  40. while (true)
  41. {
  42. byte[] data = new byte[1024];
  43. getname.isTrue = true;
  44. getname.Cleartemp();
  45. int recv = sock.ReceiveFrom(data, ref ep);
  46. string stringData = Encoding.UTF8.GetString(data, 0, recv);
  47. getname.isTrue = false ;
  48. if (ep.ToString() != null)
  49. {
  50. string[] tsIP = ep.ToString().Split(':');
  51. //getname.AddName(stringData+"_"+tsIP[0]);
  52. getname.AddName("设备"+"_"+tsIP[0]);
  53. }
  54. Debug.Log(String.Format("received: {0} from: {1}", stringData, ep.ToString()));
  55. Thread.Sleep(2000);
  56. }
  57. // sock.Close();
  58. }
  59. private void OnDestroy()
  60. {
  61. t = null;
  62. sock.Close();
  63. }
  64. }