编辑代码

using System;


public class UnityClient
{
    public string ip = "127.0.0.1";
    public int port = 4321;
    private UdpClient udpService;
    private IPEndPoint serverEP;
    private void Start()
    {
        IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(ip), port);
        udpService = new UdpClient(localEP);

        serverEP = new IPEndPoint(IPAddress.Parse(ip), 1234);
    }

    private void OnApplicationQuit()
    {
        udpService.Close();
    }

    public void SendMessage(string msg)
    {
        byte[] dgram = Encoding.UTF8.GetBytes(msg);
        udpService.Send(dgram, dgram.Length, serverEP);
    }
}


public class UnityServer
{
    private UdpClient udpService;
    private Thread thread;

    private void Start()
    {
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
        udpService = new UdpClient(ep);

        // 接收消息一旦启动,会阻塞线程的,所以不能在主线程开启,需要子线程开启
        thread = new Thread(ReceiveMessage);
        thread.Start();
    }

    private void ReceiveMessage()
    {
        while(true)
        {
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);

            byte[] data = udpService.Receive(ref remote);
            string msg = Encoding.UTF8.GetString(data);
            ThreadCrossHelper.Instance.ExecuteOnMainThread(() => 
            {
                DisplayMessage(msg);
            }); 
        }
    }

    private void DisplayMessage(string msg)
    {
        Debug.Log(msg);
    }

    private void OnApplicationQuit()
    {
        thread.Abort();
        udpService.Close();
    }
}