使用此方法有助于udp在局域网内稳定的连接运行,已经过验证,为了保持彻底的稳定,可以考虑加入ping-pang进行网络处理,如果为了安全,请使用加密TCP

如果您要在大规,大项目的游戏中使用网络技术,建议您使用:mirror,请仔细阅读下代码再进行修改,它的网络构成比较完善,但可能不太适合您的项目,仅供参考

mirror 使用比较完善的kcp技术,如果您想要了解kcp请进行网络搜索,非常建议您访问:github进行学习

 

public class NetSever : GloabManager
{
    private static NetSever _instance;
    public static NetSever Instance
    {
        get
        {
            if (_instance == null)
                _instance = new NetSever();
            return _instance;
        }
    }


    public int connectPort;
    //private Socket socket;
    private EndPoint clientEnd;
    private Thread connectThread;
    public string hostIp = null;
    public Action UI_OutlinemodeData_GameOver;
    public Text YuYinShiBie;
    public Text IP;

    public bool capture;
    public bool ColorData = false;
    public int PlayID;

    public Queue LogQueue = new Queue();


    UdpClient udpClient;
    IPEndPoint ipEnd;


    public override void Start()
    {
        base.Start();
        //初始化协议
        if (GetIP() == "")
        {
            Debug.LogError("当前IP地址不存在,或没有信号进行连接!");
            return;
        }
        udpClient = new UdpClient();
        udpClient.EnableBroadcast = true;
        connectPort = 6000;
        开启一个线程
        connectThread = new Thread(new ThreadStart(SocketReceive));
        Thread.Sleep(1000);
        connectThread.Start();
        //SendAllStart("Start+90");
    }


    public override void Update()
    {
        base.Update();
        SendMessanger();
    }

    string GetIP()
    {
        //本机名 
        string hostName = Dns.GetHostName();
        //会返回所有地址,包括IPv4和IPv6
        IPAddress[] addressList = Dns.GetHostAddresses(hostName);
        foreach (IPAddress ip in addressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }


    void SocketReceive()
    {
        UdpClient udpClient = new UdpClient(connectPort);
        try
        {
            Debug.Log("Listening for port " + connectPort + ":" + GetIP());
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                byte[] recvData = udpClient.Receive(ref remoteIpEndPoint);
                string recvStr = Encoding.UTF8.GetString(recvData);
                LogQueue.Enqueue(recvStr);
                Debug.LogError(recvStr);
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            udpClient.Close();
        }

    }
    void SendMessanger()
    {
        if (LogQueue.Count <= 0) return;
        string strArray = LogQueue.Dequeue() as string;

        //注意:此处向下处理数据,请结合项目实际

        if (strArray.Contains("+"))
        {
            var _str = strArray.Split('+');
            if (_str[0] != string.Empty)
            {
                switch (_str[0])
                {
                   
                }
            }
        }
        else
        {
            Debug.LogError("收到的信息不正确");
        }
    }


    public void SendAllStart(string content)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(content);
        udpClient.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Broadcast, connectPort));
    }
}
04-16 23:47