UdpServer.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using UnityEngine;
  9. public class UdpServer : MonoBehaviour
  10. {
  11. private static Socket sock;
  12. private static IPEndPoint iep1;
  13. private static byte[] data;
  14. private Thread t;
  15. string Error_Message;
  16. public int udpPort = 9050;
  17. private void Start()
  18. {
  19. BroadcastIP();
  20. }
  21. public void BroadcastIP()
  22. {
  23. sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  24. iep1 = new IPEndPoint(IPAddress.Broadcast, udpPort);
  25. data = Encoding.ASCII.GetBytes(SystemInfo.deviceName);
  26. sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  27. t = new Thread(BroadcastMessage);
  28. t.Start();
  29. }
  30. private void BroadcastMessage()
  31. {
  32. while (true)
  33. {
  34. sock.SendTo(data, iep1);
  35. Thread.Sleep(2000);
  36. }
  37. }
  38. private void OnDestroy()
  39. {
  40. sock.Close();
  41. }
  42. }