Exemplo n.º 1
0
        IEnumerator DownloadVideo(string MediaUrl)
        {
            UnityWebRequest webRequest    = UnityWebRequest.Get(MediaUrl);
            DownloadHandler receiveBundle = new DownloadHandlerBuffer();

            webRequest.downloadHandler = receiveBundle;
            webRequest.SendWebRequest();
            if (!Directory.Exists(Application.persistentDataPath + "/videos/"))
            {
                Directory.CreateDirectory(Application.persistentDataPath + "/videos");
            }
            string[] words        = MediaUrl.Split('/');
            string[] fileName     = words[words.Length - 1].Split('.');
            string   newLocalPath = "/videos/" + words[words.Length - 1];

            Debug.Log(Application.persistentDataPath + newLocalPath);
            while (!webRequest.isDone)
            {
                yield return(new WaitForFixedUpdate());
            }
            Debug.Log("done");
            File.WriteAllBytes(Application.persistentDataPath + newLocalPath, webRequest.downloadHandler.data);
            data.localPath = newLocalPath;
            loadAsset();
            Save();
        }
Exemplo n.º 2
0
        private static void ProcessScriptDownload(Tuple <ScriptData, string> scriptInfo, Action <ScriptData> onSuccess, Action onFail)
        {
            var www             = new UnityWebRequest(scriptInfo.item2);
            var downloadHandler = new DownloadHandlerBuffer();

            www.downloadHandler = downloadHandler;

            Logger.LogFormat("[Script Catalog] Downloading '{0}'...", scriptInfo.item1.name);

            var op = www.SendWebRequest();

            op.completed += (c) => {
                if (www.isNetworkError || www.isHttpError)
                {
                    Logger.LogFormat("[Script Catalog] <color=red>Error! Cannot download '{0}'!\n{1}...<color>",
                                     scriptInfo.item1.name, www.error);

                    onFail?.Invoke();
                }
                else
                {
                    Logger.LogFormat("[Script Catalog] Downloaded '{0}'", scriptInfo.item1.name);

                    onSuccess?.Invoke(
                        new ScriptData {
                        id     = scriptInfo.item1.id,
                        name   = scriptInfo.item1.name,
                        script = downloadHandler.text
                    });
                }

                www.Dispose();
            };
        }
        public static byte[] LoadBytes(string path)
        {
            //only extract on Android
            if (!File.Exists(path))
            {
#if UNITY_ANDROID && !UNITY_EDITOR
                var request = new UnityWebRequest(path);
                var handler = new DownloadHandlerBuffer();
                request.downloadHandler = handler;
                request.SendWebRequest();
                while (!request.isDone)
                {
                }
                if (request.error != null)
                {
                    return(null);
                }
                while (!handler.isDone)
                {
                    Thread.Sleep(100);
                }
                return(handler.data);
#else
                return(null);
#endif
            }
            return(File.ReadAllBytes(path));
        }
Exemplo n.º 4
0
        protected virtual IEnumerator DownloadAsset(SwrveAssetsQueueItem item)
        {
            string cdn = item.IsImage ? CdnImages : CdnFonts;
            string url = cdn + item.Name;

            SwrveLog.Log("Downloading asset: " + url);
            UnityWebRequest www = (item.IsImage)? UnityWebRequestTexture.GetTexture(url) : new UnityWebRequest(url);

            if (!item.IsImage)
            {
                DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
                www.downloadHandler = dH;
            }
            yield return(www.SendWebRequest());

            if (!www.isNetworkError && !www.isHttpError)
            {
                if (item.IsImage)
                {
                    SaveImageAsset(item, www);
                }
                else
                {
                    SaveBinaryAsset(item, www);
                }
            }
            else
            {
                MissingAssetsQueue.Add(item);
            }
            TaskFinished("SwrveAssetsManager.DownloadAsset");
        }
Exemplo n.º 5
0
 public static string GetFinalRedirect(string url)
 {
     if (string.IsNullOrEmpty(url))
     {
         return(url);
     }
     try
     {
         UnityWebRequest request = new UnityWebRequest(url);
         request.method = UnityWebRequest.kHttpVerbHEAD;
         DownloadHandlerBuffer response = new DownloadHandlerBuffer();
         request.downloadHandler = response;
         request.SendWebRequest();
         bool fetching = true;
         while (fetching)
         {
             if (request.isHttpError || request.isNetworkError)
             {
                 fetching = false;
                 Debug.Log(request.error);
             }
             if (request.isDone)
             {
                 fetching = false;
             }
         }
         return(request.url);
     }
     catch (Exception ex)
     {
         ex.ToString();
         return(null);
     }
 }
Exemplo n.º 6
0
        public static IPromise <T> PostForm <T>(
            string url,
            List <IMultipartFormSection> formSections,
            out Func <float> progress)
        {
            var session = Window.loginSession;
            var request = UnityWebRequest.Post(
                $"https://connect.unity.com{url}",
                formSections
                );

            request.SetRequestHeader("X-Requested-With", "XMLHTTPREQUEST");
            if (session != null && session.isNotEmpty())
            {
                request.SetRequestHeader("Cookie", $"LS={session};");
            }
            progress = () => request.uploadProgress;

            return(new Promise <T>(isSync: true, resolver: (resolve, reject) =>
            {
                request.SendWebRequest().completed += operation =>
                {
                    var content = DownloadHandlerBuffer.GetContent(request);
                    var fromProc = typeof(T).GetMethod("FromJson");
                    var response = (T)fromProc.Invoke(null, new object[] { JsonValue.Parse(content) });
                    resolve(response);
                };
            }));
        }
Exemplo n.º 7
0
        private void CreateResult()
        {
            switch (LoadType)
            {
            case LOADER_ASSETBUNDLE:
                AssetBundleCreateRequest sync = Asyncer as AssetBundleCreateRequest;
                Assets = sync.assetBundle;
                break;

            case LOADER_TEXT:
                DownloadHandler download = mRequester.downloadHandler;
                SetResultData(download.data, download.text);
                break;

            case LOADER_AUDIO_CLIP:
                AudioClip = DownloadHandlerAudioClip.GetContent(mRequester);
                break;

            case LOADER_TEXTURE:
                Texture2D   = DownloadHandlerTexture.GetContent(mRequester);
                TextureText = mRequester.downloadHandler.text;

                byte[] vs = Texture2D.GetRawTextureData();
                SetResultData(vs, TextureText);
                break;

            default:
                DownloadHandlerBuffer handler = mRequester.downloadHandler as DownloadHandlerBuffer;
                SetResultData(handler.data, handler.text);
                break;
            }
        }
Exemplo n.º 8
0
    private IEnumerator IEDownloadFile(string url, int Index, System.Action <object, bool, string> OverFun, bool IsInsert)
    {
        if (url != null && !ListidleUrl.Contains(url))
        {
            if (IsInsert)
            {
                ListidleUrl.Insert(0, url);
            }
            else
            {
                ListidleUrl.Add(url);
            }
        }
        while (!ListDownloadIng.Contains(url))
        {
            yield return(0);
        }
        object          obj        = null;
        UnityWebRequest WebRequest = UnityWebRequest.Get(url);

        WebRequest.timeout = TimeOut;
        yield return(WebRequest.Send());

        if (WebRequest.isError)
        {
            if (OverFun != null)
            {
                OverFun(obj, true, WebRequest.error);
            }
            yield break;
        }
        switch (Index)
        {
        case 1:
            obj = WebRequest.downloadHandler.data;
            break;

        case 2:
            obj = DownloadHandlerAssetBundle.GetContent(WebRequest);
            break;

        case 3:
            obj = DownloadHandlerBuffer.GetContent(WebRequest);
            break;

        case 4:
            obj = DownloadHandlerAudioClip.GetContent(WebRequest);
            break;

        case 5:
            obj = DownloadHandlerTexture.GetContent(WebRequest);
            break;
        }
        WebRequest.Dispose();
        ListDownloadIng.Remove(url);
        if (OverFun != null)
        {
            OverFun(obj, false, null);
        }
    }
Exemplo n.º 9
0
    public IEnumerator DoesUserExist(string userName, Action <bool> callback)
    {
        GetPromoCodeForUserRequest request = new GetPromoCodeForUserRequest();

        request.securityToken = HashKey.apiKey;
        request.userName      = userName;

        var jsonString = JsonUtility.ToJson(request);

        byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray());

        UnityWebRequest unityWebRequest = UnityWebRequest.Post(apiURL + "/userExists", jsonString);

        unityWebRequest.uploadHandler             = new UploadHandlerRaw(byteData);
        unityWebRequest.uploadHandler.contentType = "application/json";
        unityWebRequest.SetRequestHeader("Content-Type", "application/json");

        DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();

        unityWebRequest.downloadHandler = downloadHandlerBuffer;

        yield return(unityWebRequest.SendWebRequest());

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
        {
            Debug.Log(unityWebRequest.error);
        }
        else
        {
            string response = System.Text.Encoding.ASCII.GetString(unityWebRequest.downloadHandler.data);
            bool   userExists;
            Boolean.TryParse(response, out userExists);
            callback(userExists);
        }
    }
Exemplo n.º 10
0
    public static async Task <Score> GetHighScore()
    {
        var request = new UnityWebRequest(urlroot + "/api/v1/highest", UnityWebRequest.kHttpVerbGET);
        DownloadHandlerBuffer dH = new DownloadHandlerBuffer();

        request.downloadHandler = dH;
        request.SetRequestHeader("Content-Type", "application/json");

        await request.SendWebRequest();

        Score score = null;

        if (request.isNetworkError)
        {
            Debug.Log(request.error);
        }
        else
        {
            if (request.responseCode == 200)
            {
                score = JsonUtility.FromJson <Score>(request.downloadHandler.text);
            }
        }
        return(score);
    }
Exemplo n.º 11
0
        private IEnumerator requestQMTile(string url, Vector3 tileId)
        {
            DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
            TerrainTile           terrainTile;
            UnityWebRequest       www = new UnityWebRequest(url);

            www.downloadHandler = handler;
            yield return(www.SendWebRequest());

            if (!www.isNetworkError && !www.isHttpError)
            {
                //get data
                MemoryStream stream = new MemoryStream(www.downloadHandler.data);

                //parse into tile data structure
                terrainTile = TerrainTileParser.Parse(stream);

                //update tile with height data
                tileDb[tileId].GetComponent <MeshFilter>().sharedMesh = terrainTile.GetMesh(-44); //height offset is manually done to nicely align height data with place holder at 0
                tileDb[tileId].transform.rotation   = Quaternion.Euler(new Vector3(180, 0, 0));
                tileDb[tileId].transform.localScale = new Vector3(ComputeScaleFactor((int)tileId.z), 1, ComputeScaleFactor((int)tileId.z) * 2);
            }
            else
            {
                UnityEngine.Debug.LogError("Tile: [" + tileId.x + " " + tileId.y + "] Error loading height data");
            }

            pendingQueue.Remove(url);
            processedTileDebugCounter++;

            if (pendingQueue.Count == 0)
            {
                UnityEngine.Debug.Log("finished: with max queue size " + maxParallelRequests + ". Time: " + sw.Elapsed.TotalMilliseconds + " miliseconds. Total requests: " + processedTileDebugCounter);
            }
        }
Exemplo n.º 12
0
        private IEnumerator DoPostCall(string url, string body, System.Action <string> callback)
        {
            using (UnityWebRequest www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
            {
                DownloadHandlerBuffer dHandler = new DownloadHandlerBuffer();
                UploadHandlerRaw      uHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
                www.uploadHandler   = uHandler;
                www.downloadHandler = dHandler;
                www.SetRequestHeader("Content-Type", "application/json");
                www.SetRequestHeader("Authorization", VSettings.ValintaApplicationID);
                if (!string.IsNullOrEmpty(VSettings.SessionToken))
                {
                    www.SetRequestHeader("Client-Token", VSettings.SessionToken);
                }


                yield return(www.Send());

                if (callback != null)
                {
                    if (www.isNetworkError)
                    {
                        callback(null);
                        yield break;
                    }
                    else
                    {
                        callback(dHandler.text);
                    }
                }
            }
        }
        private IEnumerator RequestTerrainTile(string url, Vector3 tileId)
        {
            DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
            TerrainTile           terrainTile;
            var www = new UnityWebRequest(url)
            {
                downloadHandler = handler
            };

            yield return(www.SendWebRequest());

            if (!www.isNetworkError && !www.isHttpError)
            {
                //get data
                var stream = new MemoryStream(www.downloadHandler.data);

                //parse into tile data structure
                terrainTile = TerrainTileParser.Parse(stream);

                //update tile with height data
                tileDb[tileId].GetComponent <MeshFilter>().sharedMesh = terrainTile.GetMesh(-44); //height offset is manually done to nicely align height data with place holder at 0
                tileDb[tileId].transform.localScale = new Vector3(ComputeScaleFactorX((int)tileId.z), 1, ComputeScaleFactorY((int)tileId.z));
            }
            else
            {
                Debug.Log("Tile: [" + tileId.x + " " + tileId.y + "] Error loading height data" + " url:  " + url);
            }

            pendingQueue.Remove(url);
        }
Exemplo n.º 14
0
        private IEnumerator RequestBuildingTile(string url, Vector3 offset)
        {
            DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
            var www = new UnityWebRequest(url)
            {
                downloadHandler = handler
            };

            yield return(www.SendWebRequest());

            if (!www.isNetworkError && !www.isHttpError)
            {
                //get data
                var stream = new MemoryStream(www.downloadHandler.data);

                var b3dm = B3dmParser.ParseB3dm(stream); //set to false because currently no batchtable is supplied in adam datasources. When adding eg. BagID's, this needs to be set to true + plus batchtable implementation.
                //Debug.Log(b3dm.Glb.GltfModelJson);
                var memoryStream = new MemoryStream(b3dm.GlbData);
                Load(memoryStream);
            }
            else
            {
                Debug.Log("Tile: [" + url + "] Error loading b3dm data");
            }

            pendingQueue.Remove(url);
        }
Exemplo n.º 15
0
        // 加载本地version文件
        private static IEnumerator LoadVersionFile(string fileUrl, DataContainer dataContainer, Action onComplete = null)
        {
            Log("LoadVersionFile :{0}", fileUrl);


            UnityWebRequest       www         = new UnityWebRequest(fileUrl);
            DownloadHandlerBuffer downHandler = new DownloadHandlerBuffer();

            www.downloadHandler = downHandler;
            yield return(www.SendWebRequest());

            if (string.IsNullOrEmpty(www.error))
            {
                Log("LoadVersionFile www.text:{0}", www.downloadHandler.text);
                dataContainer.strData = www.downloadHandler.text;
                www.Dispose();
                if (onComplete != null)
                {
                    onComplete();
                }
                Log("Finish load version file with WWW:{0}", fileUrl);
                yield break;
            }
            else
            {
                DebugUtil.LogError("load version file {0} fail,error:{1}", fileUrl, www.error);
            }
        }
Exemplo n.º 16
0
    public IEnumerator AddUser(User user, Action <User> callback)
    {
        AddUserRequest request = new AddUserRequest();

        request.user          = user;
        request.securityToken = HashKey.apiKey;

        var jsonString = JsonUtility.ToJson(request);

        byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray());

        //UnityWebRequest unityWebRequest = UnityWebRequest.Post(apiURL + "/user", jsonString);
        UnityWebRequest unityWebRequest = new UnityWebRequest(apiURL + "/user", "POST");

        unityWebRequest.uploadHandler             = new UploadHandlerRaw(byteData);
        unityWebRequest.uploadHandler.contentType = "application/json";
        unityWebRequest.SetRequestHeader("Content-Type", "application/json");


        DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();

        unityWebRequest.downloadHandler = downloadHandlerBuffer;

        yield return(unityWebRequest.SendWebRequest());

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
        {
            Debug.Log(unityWebRequest.error);
        }
        else
        {
            string response = unityWebRequest.downloadHandler.text;
            callback(JsonUtility.FromJson <User>(response));
        }
    }
Exemplo n.º 17
0
        private IEnumerator Post(string url, string payload, Action <bool> callBack = null)
        {
            var jsonBinary = System.Text.Encoding.UTF8.GetBytes(payload);

            DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();

            UploadHandlerRaw uploadHandlerRaw = new UploadHandlerRaw(jsonBinary);

            uploadHandlerRaw.contentType = "application/json";

            UnityWebRequest www =
                new UnityWebRequest(url, "POST", downloadHandlerBuffer, uploadHandlerRaw);

            yield return(www.SendWebRequest());

            if (www.isNetworkError)
            {
                Debug.LogError(string.Format("{0}: {1}", www.url, www.error));
            }
            else
            {
                Debug.Log(string.Format("Response: {0}", www.downloadHandler.text));
            }

            callBack?.Invoke(!www.isNetworkError);
        }
Exemplo n.º 18
0
    public IEnumerator GetPromoCodesForUser(string userName, Action <List <PromoCode> > callback)
    {
        GetPromoCodeForUserRequest request = new GetPromoCodeForUserRequest();

        request.userName      = userName;
        request.securityToken = HashKey.apiKey;

        var jsonString = JsonUtility.ToJson(request);

        byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray());

        UnityWebRequest unityWebRequest = UnityWebRequest.Post(apiURL + "/userPromoCodes", jsonString);

        unityWebRequest.uploadHandler             = new UploadHandlerRaw(byteData);
        unityWebRequest.uploadHandler.contentType = "application/json";
        unityWebRequest.SetRequestHeader("Content-Type", "application/json");

        DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();

        unityWebRequest.downloadHandler = downloadHandlerBuffer;

        yield return(unityWebRequest.SendWebRequest());

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
        {
            Debug.Log(unityWebRequest.error);
            callback(null);
        }
        else
        {
            string      response = unityWebRequest.downloadHandler.text;
            PromoCode[] codes    = JsonHelper.FromJsonWithFix <PromoCode>(response);
            callback(new List <PromoCode>(codes));
        }
    }
Exemplo n.º 19
0
        public static IPromise <T> Post <T>(
            string url,
            string data)
        {
            return(new Promise <T>(isSync: true, resolver: (resolve, reject) =>
            {
                var session = Window.loginSession;
                var request = new UnityWebRequest(
                    $"https://connect.unity.com{url}",
                    UnityWebRequest.kHttpVerbPOST
                    )
                {
                    downloadHandler = new DownloadHandlerBuffer(),
                };
                if (data != null)
                {
                    request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
                }
                request.SetRequestHeader("X-Requested-With", "XMLHTTPREQUEST");
                request.SetRequestHeader("Content-Type", "application/json");
                if (session != null && session.isNotEmpty())
                {
                    request.SetRequestHeader("Cookie", $"LS={session};");
                }

                request.SendWebRequest().completed += operation =>
                {
                    var content = DownloadHandlerBuffer.GetContent(request);
                    var fromProc = typeof(T).GetMethod("FromJson");
                    var response = (T)fromProc.Invoke(null, new object[] { JsonValue.Parse(content) });
                    resolve(response);
                };
            }));
        }
Exemplo n.º 20
0
    public static IEnumerator RunAICoroutine(float time, float deltaTime, AI_Input input, System.Action <AI_Output> callBack)
    {
        // Process the results and setup a new test
        UploadHandler uploader = new UploadHandlerRaw(GetRunAIRequestBody(time, deltaTime, input));

        uploader.contentType = "application/json";
        var downloader = new DownloadHandlerBuffer();
        var wr         = new UnityWebRequest("http://localhost:8888/handleInput/", "POST", downloader, uploader);

        yield return(wr.Send());

        if (downloader.isDone)
        {
            // Update the AI model based on server response
            var output = GetRunOutput(downloader.data);

            // Move the car
            callBack(output);

            // Save evaluation
            evaluationResults.Add(new AI_Evaluation {
                time   = time,
                input  = input,
                output = output
            });
        }
        else
        {
            Debug.logger.LogWarning("AI_Logic [RunAI]", "Invalid server response.");
        }
    }
Exemplo n.º 21
0
    IEnumerator PostRequest()
    {
        UnityWebRequest www = new UnityWebRequest("https://api.lace.guide/graph/getGraphModel", "POST");

        DownloadHandlerBuffer dH = new DownloadHandlerBuffer();

        www.downloadHandler = dH;

        www.SetRequestHeader("Content-Type", "application/json");
        www.SetRequestHeader("auth", "afjCEsnkK3bJ@#$dz%3JRTMtWJIAZs@Cc$Me*%!KkXpNR9G1MS$2xtfn5!FfGsy!caK5#kVd4l%ghDyFWp2jAVGaPYdAaerCDW9Snu0G#IOXVBIb*uCx5gt7O0&c1&tUg#G7Nd5nUHTQM7d32nzRlRa3D&WqWN9y&Bqe3SCv7C*mS4LFV5kM37wFbgDgvjELZI%mvx*v&a!w0Ie3XWy$Gdu6NJJUJ#eN^&Q!pCUVyWkZ9B7py8p^a*92r80iOrX3v@BSREqS^MEkx3$#2kUtP%#X5Oq!L*Ovg9Fg5$6xR0oX");

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            string data = www.downloadHandler.text;

            data = data.Trim('[');
            data = data.Trim(']');

            Global.Instance.response = JsonConvert.DeserializeObject <Response>(data);

            yield return(Global.Instance.response);

            Global.Instance.responseObtained = true;
        }
    }
Exemplo n.º 22
0
    public static IEnumerator RunEvaluationCoroutine(float survivalTime, float traveledDistance, float furthestDistance, Action resetCallBack)
    {
        Debug.logger.Log("Crashed. Processing results... survival time: " + survivalTime);

        // Process the results and setup a new test
        UploadHandler uploader = new UploadHandlerRaw(GetEvaluationRequestBody(traveledDistance, furthestDistance, survivalTime));

        uploader.contentType = "application/json";
        var downloader = new DownloadHandlerBuffer();
        var wr         = new UnityWebRequest("http://localhost:8888/sendEvaluation/", "POST", downloader, uploader);

        yield return(wr.Send());

        if (downloader.isDone)
        {
            // Update the AI model based on server response
            UpdateModelJson(downloader.data);
        }
        else
        {
            Debug.logger.LogWarning("AI_Logic [RunEvaluation]", "Invalid server response.");
        }

        Debug.logger.Log("Restarting...");
        resetCallBack();
    }
Exemplo n.º 23
0
    bool serverListUpdate = false;//是否成功更新了服务器,如果更新了,选择的服务器为第一个服务器,否则不设定服务器
    IEnumerator UpdateServiceList()
    {
        UnityWebRequest vFile = new UnityWebRequest();

        vFile.url     = string.Format(Main.strFile, Main.strHost, Main.port, Main.strProjectUrl, Main.strServices);
        vFile.timeout = 2;
        DownloadHandlerBuffer dH = new DownloadHandlerBuffer();

        vFile.downloadHandler = dH;
        yield return(vFile.Send());

        if (vFile.isNetworkError || vFile.responseCode != 200 || string.IsNullOrEmpty(dH.text))
        {
            Debug.LogError(string.Format("update version file error:{0} or responseCode:{1}", vFile.error, vFile.responseCode));
            vFile.Dispose();
            Update = null;
            CombatData.Ins.Servers.Clear();
            for (int i = 0; i < GameStateMgr.Ins.gameStatus.ServerList.Count; i++)
            {
                CombatData.Ins.Servers.Add(GameStateMgr.Ins.gameStatus.ServerList[i]);
            }
            serverListUpdate = false;
            OnGetServerListDone();
            yield break;
        }
        serverListUpdate = true;
        CombatData.Ins.Servers.Clear();
        LitJson.JsonData js = LitJson.JsonMapper.ToObject(dH.text);
        for (int i = 0; i < js["services"].Count; i++)
        {
            ServerInfo s = new ServerInfo();
            if (!int.TryParse(js["services"][i]["port"].ToString(), out s.ServerPort))
            {
                continue;
            }
            if (!int.TryParse(js["services"][i]["type"].ToString(), out s.type))
            {
                continue;
            }
            if (s.type == 0)
            {
                s.ServerHost = js["services"][i]["addr"].ToString();
            }
            else
            {
                s.ServerIP = js["services"][i]["addr"].ToString();
            }
            s.ServerName = js["services"][i]["name"].ToString();
            CombatData.Ins.Servers.Add(s);
        }
        Update = null;

        //合并所有服务器到全局变量里
        for (int i = 0; i < GameStateMgr.Ins.gameStatus.ServerList.Count; i++)
        {
            CombatData.Ins.Servers.Add(GameStateMgr.Ins.gameStatus.ServerList[i]);
        }

        OnGetServerListDone();
    }
    IEnumerator ServerConnect() //서버 연결 - SimonOrder 주석 참고
    {
        using (UnityWebRequest www = new UnityWebRequest(PatientInfoURL, UnityWebRequest.kHttpVerbGET))
        {
            DownloadHandlerBuffer dH = new DownloadHandlerBuffer();

            www.downloadHandler = dH;
            www.SetRequestHeader("Content-Type", "application/json");
            yield return(www.SendWebRequest());

            if (www.isHttpError || www.isNetworkError)
            {
                Debug.Log(www.error);
            }
            else
            {
                jsonstring = www.downloadHandler.text;

                if (!jsonstring.Equals("[]") && !jsonstring.Equals(""))
                {
                    var playerData = JsonConvert.DeserializeObject <PatientInfo>(jsonstring);

                    if (playerData != null)
                    {
                        Patient = new PatientInfo
                        {
                            UserID = playerData.UserID,
                            Name   = playerData.Name,
                            Level  = playerData.Level
                        };
                    }
                }
            }
        }
    }
Exemplo n.º 25
0
        /// <summary>
        /// Downloads a series of scripts from the internet
        /// </summary>
        /// <param name="url">The url of the script manifest</param>
        /// <param name="urlPrefix">The root url</param>
        /// <param name="onScriptDownload">The event where a script was downloaded</param>
        /// <param name="onComplete">The event called when the entire process is complete</param>
        internal static void DownloadScripts(string url, string urlPrefix, Action <ScriptData> onScriptDownload, Action onComplete)
        {
            var www     = UnityWebRequest.Get(url);
            var handler = new DownloadHandlerBuffer();

            www.downloadHandler = handler;
            var op = www.SendWebRequest();

            op.completed += c => {
                var json          = JsonMapper.ToObject(handler.text);
                var array         = json[0];
                var downloadQueue = new DownloadQueue();

                for (var i = 0; i < array.Count; ++i)
                {
                    var datum = array[i];

                    var scriptData = new ScriptData {
                        id   = (uint)datum["id"],
                        name = datum["name"].GetString()
                    };

                    var scriptUrl = string.Format("{0}{1}", urlPrefix, datum["asset-path"]);
                    downloadQueue.Enqueue(new Tuple <ScriptData, string> (scriptData, scriptUrl));
                }

                ProcessDownloadQueue(downloadQueue, onScriptDownload, onComplete);
            };
        }
    private IEnumerator DownloadB3DMTile(string url)
    {
        DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
        var www = new UnityWebRequest(@"https://saturnus.geodan.nl/tomt/data/buildingtiles_adam/" + url)
        {
            downloadHandler = handler
        };

        yield return(www.SendWebRequest());

        if (!www.isNetworkError && !www.isHttpError)
        {
            //get data
            var stream = new MemoryStream(www.downloadHandler.data);

            var b3dm = B3dmParser.ParseB3dm(stream);

            var memoryStream = new MemoryStream(b3dm.GlbData);
            Load(memoryStream);
        }
        else
        {
            Debug.Log("Tile: [" + url + "] Error loading b3dm data");
        }
    }
Exemplo n.º 27
0
            private void Load()
            {
                _loading    = true;
                _imageMetas = new Dictionary <string, ImageMeta>();
                var version = DocApp.of(context).version;
                var url     =
                    $"{Configuration.Instance.cdnPrefix}/{version.unityVersion}/{version.parsedVersion}/scripting/json/{widget._title.Replace('-', '_')}.json";
                var request        = UnityWebRequest.Get(url);
                var asyncOperation = request.SendWebRequest();

                asyncOperation.completed += operation =>
                {
                    if (!mounted)
                    {
                        return;
                    }

                    using (WindowProvider.of(context).getScope())
                    {
                        var content   = DownloadHandlerBuffer.GetContent(request);
                        var scripting = JsonConvert.DeserializeObject <Models.Json.Scripting>(content);
                        setState(() =>
                        {
                            _scripting  = scripting;
                            _loading    = false;
                            _imageMetas = scripting.imageMetas?.ToDictionary(
                                meta => meta.name,
                                meta => meta);
                        });
                    }
                };
            }
Exemplo n.º 28
0
        public override IEnumerator DownLoad()
        {
            // Check fatal
            if (States != EWebRequestStates.None)
            {
                throw new Exception($"{nameof(WebDataRequest)} is downloading yet : {URL}");
            }

            States = EWebRequestStates.Loading;

            // 下载文件
            CacheRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
            DownloadHandlerBuffer handler = new DownloadHandlerBuffer();

            CacheRequest.downloadHandler = handler;
            CacheRequest.disposeDownloadHandlerOnDispose = true;
            CacheRequest.timeout = Timeout;
            yield return(CacheRequest.SendWebRequest());

            // Check error
            if (CacheRequest.isNetworkError || CacheRequest.isHttpError)
            {
                MotionLog.Log(ELogLevel.Warning, $"Failed to download web data : {URL} Error : {CacheRequest.error}");
                States = EWebRequestStates.Fail;
            }
            else
            {
                States = EWebRequestStates.Success;
            }
        }
Exemplo n.º 29
0
 private static UnityWebRequest _postBytes(string url, byte[] bytes, CLAssetType type,
                                           object successCallback,
                                           object failedCallback, object orgs, bool isCheckTimeout,
                                           int maxFailTimes, int failedTimes)
 {
     try
     {
         self.enabled = true;
         UnityWebRequest       www             = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
         UploadHandlerRaw      MyUploadHandler = new UploadHandlerRaw(bytes);
         DownloadHandlerBuffer downloadHandler = new DownloadHandlerBuffer();
         //MyUploadHandler.contentType = "application/x-www-form-urlencoded"; // might work with 'multipart/form-data'
         www.uploadHandler   = MyUploadHandler;
         www.downloadHandler = downloadHandler;
         Coroutine cor = self.StartCoroutine(
             self.exeWWW(www, url, type, successCallback, failedCallback, orgs, isCheckTimeout, maxFailTimes, failedTimes,
                         (url2) =>
         {
             _postBytes(url2, bytes, type, successCallback, failedCallback, orgs, isCheckTimeout, maxFailTimes, failedTimes + 1);
         }));
         wwwMap4Get[url] = cor;
         return(www);
     }
     catch (System.Exception e)
     {
         Debug.LogError(e);
         Utl.doCallback(failedCallback, null, orgs);
         return(null);
     }
 }
Exemplo n.º 30
0
            #pragma warning restore 612, 618

            #if WEB_REQUEST_SUPPORTED
            static private IEnumerator DownloadBytesRoutine(Future <byte[]> inFuture, UnityWebRequest inWebRequest)
            {
                using (inWebRequest)
                {
                    var downloadHandler = new DownloadHandlerBuffer();
                    inWebRequest.downloadHandler = downloadHandler;
                    AsyncOperation op = UnityWebRequest_SendWebRequest(inWebRequest);
                    while (!op.isDone)
                    {
                        yield return(null);

                        inFuture.SetProgress(inWebRequest.downloadProgress);
                    }
                    if (!UnityWebRequest_IsError(inWebRequest))
                    {
                        try
                        {
                            inFuture.Complete(downloadHandler.data);
                        }
                        catch (Exception e)
                        {
                            inFuture.Fail(Future.FailureType.Exception, e);
                        }
                    }
                    else
                    {
                        inFuture.Fail(Future.FailureType.Unknown, inWebRequest.error);
                    }
                    yield return(null);
                }
            }