当前位置:网站首页>Unity C # e-learning (IX) -- wwwfrom

Unity C # e-learning (IX) -- wwwfrom

2022-06-26 15:05:00 Handsome_ shuai_

Unity C# E-learning ( Nine )——WWWFrom

  • If you want to use WWW When uploading data , We need to cooperate WWWFrom Class
  • The main request types used are Post
  • Use WWWFrom Uploading data generally needs to cooperate with the back-end program to formulate upload rules

One .WWWFrom class

1.WWWFrom Common methods of class

        WWWForm wwwForm = new WWWForm();
        //1. Add binary data 
        wwwForm.AddBinaryData("xxx", new byte[10]);
        //2. Add fields 
        wwwForm.AddField("name", "zzs", Encoding.UTF8);

2.WWW combination WWWFrom Object to asynchronously upload data

    private IEnumerator UpLoadData()
    {
    
        WWWForm data = new WWWForm();
        data.AddField("Name", "zzs", Encoding.UTF8);
        data.AddField("Age", 18);
        data.AddBinaryData("file",File.ReadAllBytes(Application.streamingAssetsPath +"/test.jpg"),"myTest.jpg","application/octet-stream");
        
        WWW www = new WWW("http://192.168.1.103:8080/Http_Server/", data);
        yield return www;
        if (www.error == null && www.isDone)
        {
    
            Debug.Log(" Upload successful !");
        }
        else
        {
    
            Debug.Log(" Upload failed !" + www.error);
        }
    }

Two .WWWFrom send data

    public void SendMsg<T>(MsgBase msg,Action<T> action) where T: MsgBase
    {
    
        StartCoroutine(SendMsgAsync(msg,action));
    }
    private IEnumerator SendMsgAsync<T>(MsgBase msg,Action<T> action)where T: MsgBase
    {
    
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddBinaryData("Msg",msg.ToArray());
        WWW www = new WWW(RootUrl,wwwForm);
        yield return www;
        if (www.error == null)
        {
    
            int index = 0;
            int msgId = BitConverter.ToInt32(www.bytes, 0);
            index += 4;
            int length = BitConverter.ToInt32(www.bytes, index);
            index += 4;
            MsgBase msgBase = null;
            switch (msgId)
            {
    
                case 1001:
                    msgBase = new PlayerMsg();
                    msgBase.Reading(www.bytes, index);
                    break;
            }

            if (msgBase != null)
            {
    
                action?.Invoke(msgBase as T);
            }
        }
        else
        {
    
            Debug.Log(" There was a problem sending messages :"+www.error);
        }
    }
原网站

版权声明
本文为[Handsome_ shuai_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261447242138.html

随机推荐