Unity 获取服务器时间 HTTP请求方式

在写每日签到的时候,我居然使用的是本地时间...被项目经理笑哭了。。。。, 如果你在写单机游戏,没有游戏服务器,但又不想使用本地时间,就可以采用下面方法.

方法总结:

      1. 使用HTTP请求获取服务器时间,不能实时获取服务器时间这样高频率的

      2. 使用socket可以实时获取服务器时间

      3. 使用C#自带API获取sql server 标准北京时间(=。=还没有找到这个API)

第HTTP方式:

image

代码:

 

using UnityEngine;
using System.Collections;
using System.Timers;
using System;
using System.Text.RegularExpressions;

public class Test : MonoBehaviour {


    private string url = "http://www.beijing-time.org/time.asp";            //免费获取背景时间的Wbe 接口
    private string time = string.Empty;


    void OnGUI() 
    {
        if(GUI.Button(new Rect(0,0,100,100),"获取北京时间"))
        {
            StartCoroutine(GetTime());
        }

        GUI.Label(new Rect(0, 100, 300, 300), "时间:" + time);
    }

    IEnumerator GetTime() 
    {
        Debug.Log("开始请求服务器");
        WWW www = new WWW(url);
        yield return www;                   //在这里阻塞,等待响应之后返回
        if (www.isDone && string.IsNullOrEmpty(www.error))
        {
            SpliitString(www);
        }
    }


    public void SpliitString(WWW www)
    {
        //使用正则表达式匹配
        string patten = @"[0-9]{1,};";
        Regex regex = new Regex(patten);
        MatchCollection result = regex.Matches(www.text);
        //组织时间
        time = string.Format("{0}-{1}-{2} {3}:{4}:{5}"
                        , result[0].Value.TrimEnd(';')
                        , result[1].Value.TrimEnd(';')
                        , result[2].Value.TrimEnd(';')
                        , result[4].Value.TrimEnd(';')
                        , result[5].Value.TrimEnd(';')
                        , result[6].Value.TrimEnd(';')
                        );


        Debug.Log("北京时间:" + time);
    }


}

 

原文地址: http://www.chengxuyuans.com/Android/63647.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章