Unity C# 网络学习(九)——WWWFrom

Unity C# 网络学习(九)——WWWFrom

  • 如果想使用WWW上传数据时,就需要配合WWWFrom类进行使用了
  • 它主要用到的请求类型是Post
  • 使用WWWFrom上传数据一般需要配合后端程序制定上传规则

一.WWWFrom类

1.WWWFrom类的常用方法

        WWWForm wwwForm = new WWWForm();
        //1.添加二进制数据
        wwwForm.AddBinaryData("xxx", new byte[10]);
        //2.添加字段
        wwwForm.AddField("name", "zzs", Encoding.UTF8);

2.WWW结合WWWFrom对象来异步上传数据

    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("上传成功!");
        }
        else
        {
    
    
            Debug.Log("上传失败!" + www.error);
        }
    }

二.WWWFrom 发送数据

    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("发消息出现问题:"+www.error);
        }
    }

猜你喜欢

转载自blog.csdn.net/zzzsss123333/article/details/125462120