Unity UDP 브로드캐스트 수신자 구현


public class Lighthouse : MonoBehaviour
{
    private byte[] data;
    private string Error_Message;
    private Thread thread;
    private EndPoint ep;
    private bool IsStop = false;
    private Socket socket;
    public int udpPort = 9050;
    public static Lighthouse instance;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            GetSeverIP();
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void GetSeverIP()
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            ep = new IPEndPoint(IPAddress.Any, udpPort);
            socket.Bind(ep);
            data = new byte[1024];
            thread = new Thread(Receive);
            thread.IsBackground = true;
            thread.Start();
        }
        catch (Exception e)
        {
            Debug.LogError(" :" + e.Message);
        }

    }


    private void Receive()
    {
        while (!IsStop)
        {
            if (socket.Available <= 0) continue;
            int recv = socket.ReceiveFrom(data, ref ep);
            string msg = Encoding.ASCII.GetString(data, 0, recv);
            Debug.Log(" :"+msg);
        }
    }


    public void OnApplicationQuit()
    {
        IsStop = true;
        socket.Shutdown(SocketShutdown.Both);
        socket.Close();
        thread.Abort();
    }

}

좋은 웹페이지 즐겨찾기