Unity 之 Ping类简析&尝试使用

Ping 什么意思???

【来自百度百科的诠释:】 Ping是Windows、Unix和Linux系统下的一个命令。ping也属于一个通信协议,是TCP/IP协议的一部分。利用“ping”命令可以检查网络是否连通,可以很好地帮助我们分析和判定网络故障。应用格式:ping空格IP地址。该命令还可以加许多参数使用,具体是键入ping按回车即可看到详细说明。

Unity Ping:

ping操作是异步的,可以使用ping.isDone对ping对象进行状态轮询。当收到答复时,它在ping.time。 注意:在WindowsStore应用程序上,流套接字用于模拟ping功能,它将尝试打开与端口80的指定IP地址的连接。此外,您还需要在Package.appx清单中启用InternetClient功能。

官方文档:https://docs.unity3d.com/2017.2/Documentation/ScriptReference/Ping.html


文档上,只体现了三个属性和一个方法,,,程序集源码如下:

#region 程序集 UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// E:\program files\Unity\Editor\Data\Managed\UnityEngine.dll
#endregion

using UnityEngine.Scripting;

namespace UnityEngine
{
    //
    // 摘要:
    //     Ping any given IP address (given in dot notation).
    //Ping任何给定的IP地址(用点符号表示)。
    public sealed class Ping
    {
        //
        // 摘要:
        //     Perform a ping to the supplied target IP address.
        //     对提供的目标IP地址执行ping。
        // 参数:
        //   address: ip地址
        [GeneratedByOldBindingsGeneratorAttribute]
        public Ping(string address);

        ~Ping();

        //
        // 摘要:
        //     Has the ping function completed?
        //     ping功能完成了吗?
        public bool isDone { get; }
        //
        // 摘要:
        //     This property contains the ping time result after isDone returns true.
        //     此属性包含isDone返回true后的ping时间结果。
        public int time { get; }
        //
        // 摘要:
        //     The IP target of the ping.
        //     ping的IP目标。
        public string ip { get; }

        [GeneratedByOldBindingsGeneratorAttribute]
        [ThreadAndSerializationSafeAttribute]
        public void DestroyPing();
    }
}

尝试写了一下,发现并不好用,代码如下:【期待大佬留言纠错,指点】

using System.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using UnityEngine;

public class UnityPing : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(CheckPing());
    }

    IEnumerator CheckPing()
    {
        //Ping服务器 
        Ping ping = new Ping("服务器IP");

        int time = 0;

        Debug.Log("开始尝试连接... : " + ping.isDone);
        while (!ping.isDone)
        {
            yield return new WaitForSeconds(0.1f);
            if (nTime > 20) //2秒
            {
                Debug.Log("连接失败 ... " + ping.time);
                yield break;
            }
            time ++;
        }
        if (ping.isDone)
        {
            yield return ping.time;
            Debug.Log("连接成功... 就没成功过");
        }
    }
 }


文末分享一个Unity ping一个服务器 ip 的工具类 ,原文链接:https://gameinstitute.qq.com/community/detail/126598

ps:原文的大括号是中文字符,如有使用建议直接复制下文代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnityPing : MonoBehaviour
{

    private static string s_ip = "";
    private static System.Action<int> s_callback = null;
    private static UnityPing s_unityPing = null;
    private static int s_timeout = 2;
    public static void CreatePing(string ip, System.Action<int> callback)
    {
        if (string.IsNullOrEmpty(ip)) return;
        if (callback == null) return;
        if (s_unityPing != null) return;
        s_ip = ip;
        s_callback = callback;
        GameObject go = new GameObject("UnityPing");
        DontDestroyOnLoad(go);
        s_unityPing = go.AddComponent<UnityPing>();
    }
    /// <summary>
    /// 超时时间(单位秒)
    /// </summary>
    public static int Timeout
    {
        set
        {
            if (value > 0)
            {
                s_timeout = value;
            }
        }
        get { return s_timeout; }
    }
    private void Start()
    {
        switch (Application.internetReachability)
        {
            case NetworkReachability.ReachableViaCarrierDataNetwork: // 3G/4G
            case NetworkReachability.ReachableViaLocalAreaNetwork: // WIFI
                {
                    StopCoroutine(this.PingConnect());
                    StartCoroutine(this.PingConnect());
                }
                break;
            case NetworkReachability.NotReachable: // 网络不可用
            default:
                {
                    if (s_callback != null)
                    {
                        s_callback(-1);
                        Destroy(this.gameObject);
                    }
                }
                break;
        }
    }
    private void OnDestroy()
    {
        s_ip = "";
        s_timeout = 20;
        s_callback = null;
        if (s_unityPing != null)
        {
            s_unityPing = null;
        }
    }
    IEnumerator PingConnect()
    {
        // Ping网站
        Ping ping = new Ping(s_ip);
        int addTime = 0;
        int requestCount = s_timeout * 10; // 0.1秒 请求 1 次,所以请求次数是 n秒 x 10
        // 等待请求返回
        while (!ping.isDone)
        {
            yield return new WaitForSeconds(0.1f);
            // 链接失败
            if (addTime > requestCount)
            {
                addTime = 0;
                if (s_callback != null)
                {
                    s_callback(ping.time);
                    Destroy(this.gameObject);
                }
                yield break;
            }
            addTime++;
        }
        // 链接成功
        if (ping.isDone)
        {
            if (s_callback != null)
            {
                s_callback(ping.time);
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
}
发布了446 篇原创文章 · 获赞 630 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/Czhenya/article/details/93536269