UdpClient.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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.ASCII.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. }
  53. Debug.Log(String.Format("received: {0} from: {1}", stringData, ep.ToString()));
  54. Thread.Sleep(2000);
  55. }
  56. // sock.Close();
  57. }
  58. private void OnDestroy()
  59. {
  60. t = null;
  61. sock.Close();
  62. }
  63. }