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();
    }

}

 

你可能感兴趣的:(unity,C#脚本,C#,Unity)