当前位置: 首页 > news >正文

Unity网络开发--超文本传输协议Http(2)

Unity相关类

UnityWebRequest

Get获取操作

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;public class lesson10_4 : MonoBehaviour
{public RawImage image;// Start is called before the first frame updatevoid Start(){//UnityWebRequest 是什么?//UnityWebRequest 是一个 Unity 提供的一个模块化的系统类// 用于构成 HTTP 请求和处理 HTTP 响应// 它主要目标是让 Unity 游戏和 Web 服务器进行交互// 它将之前 WWW 的相关功能都集成在了其中// 所以新版本中都建议使用 UnityWebRequest 类来代替 WWW 类// 它在使用上和 WWW 很类似// 主要的区别就是 UnityWebRequest 把下载下来的数据处理单独提取出来了// 我们可以根据自己的需求选择对应的数据处理对象来获取数据// 注意://1.UnityWebRequest 和 WWW 一样,需要配合协同程序使用//2.UnityWebRequest 和 WWW 一样,支持 http、ftp、file 协议下载或加载资源//3.UnityWebRequest 能够上传文件到 HTTP 资源服务器//Get获取操作StartCoroutine(LoadText());StartCoroutine(LoadTexture());}IEnumerator LoadText(){UnityWebRequest request = UnityWebRequest.Get("http://192.168.80.1:8080/httpServer/test.txt");//等待服务器端响应后 断开连接后 再继续执行后面的内容yield  return  request.SendWebRequest();if (request.result == UnityWebRequest.Result.Success){//文本字符串print(request.downloadHandler.text);//字节数组byte[] bytes = request.downloadHandler.data;}else{print("获取失败:" + request.result + request.error + request.responseCode);}}IEnumerator LoadTexture(){UnityWebRequest request = UnityWebRequestTexture.GetTexture("http://192.168.80.1:8080/httpServer/Http上传的文件.png");request.SendWebRequest();while (!request.isDone){print(request.downloadProgress);print(request.downloadedBytes);yield return null;}if (request.result == UnityWebRequest.Result.Success){//(request.downloadHandler as DownloadHandlerTexture).textureimage.texture = DownloadHandlerTexture.GetContent(request);}else{print("获取失败:" + request.result + request.error + request.responseCode);}}IEnumerator LoadAB(){UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle("");yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.Success){DownloadHandlerAssetBundle.GetContent(request);}else{print("获取失败:" + request.result + request.error + request.responseCode);}}// Update is called once per framevoid Update(){}
}

Post上传操作和Put上传操作

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;public class lesson10_5 : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){//上传相关数据类// 父接口//IMultipartFormSection// 数据相关类都继承该接口// 我们可以用父类装子类List<IMultipartFormSection> dataList = new List<IMultipartFormSection>();// 子类数据//MultipartFormDataSection//1. 二进制字节数组dataList.Add(new MultipartFormDataSection(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxx")));//2. 字符串dataList.Add(new MultipartFormDataSection("xxxxxxxxxxxxx"));//3. 参数名,参数值(字节数组,字符串),编码类型,资源类型(常用)dataList.Add(new MultipartFormDataSection("Name", "xxx", Encoding.UTF8, "application/HTTP中的POST消息类型"));dataList.Add(new MultipartFormDataSection("Msg", new byte[1024], "application/HTTP中的POST消息类型"));//MultipartFormFileSection//1. 字节数组dataList.Add(new MultipartFormFileSection(File.ReadAllBytes(Application.streamingAssetsPath + "/test.png")));//2. 文件名,字节数组(常用)dataList.Add(new MultipartFormFileSection("上传的文件名.png", File.ReadAllBytes(Application.streamingAssetsPath + "/test.png")));//3. 字符串数据,文件名(常用)dataList.Add(new MultipartFormFileSection("xxxxxxxxxxxx","创建的文本文件.txt"));//4. 字符串数据,编码格式,文件名(常用)dataList.Add(new MultipartFormFileSection("xxxxxxxxxxxx",Encoding.UTF8, "创建的文本文件.txt"));//5. 表单名,字节数组,文件名,文件类型dataList.Add(new MultipartFormFileSection("file",new byte[1024], "创建的文件名称.txt", "application/HTTP中的POST消息类型"));//6. 表单名,字符串数据,编码格式,文件名dataList.Add(new MultipartFormFileSection("file", "xxxxxxxx",Encoding.UTF8, "创建的文件名称.txt"));//Post发送相关StartCoroutine(Upload());//Put上传相关//Put请求类型不是所有的web服务器都认,必须要服务器处理该请求类型那么才能响应StartCoroutine(UpLoadPut());}IEnumerator Upload(){//准备上传的数据List<IMultipartFormSection> data = new List<IMultipartFormSection>();//键值对相关的信息 字段数据data.Add(new MultipartFormDataSection("Name", "XXXX"));PlayerMsg player = new PlayerMsg();player.playerID = 0;player.playerData = new PlayerData();player.playerData.name = "xxxxxx";player.playerData.atk = 10;player.playerData.lev = 11;data.Add(new MultipartFormDataSection("Msg",player.Writing()));//添加一些文件上传文件data.Add(new MultipartFormFileSection("lesson10.png", File.ReadAllBytes( Application.streamingAssetsPath + "/test.png")));data.Add(new MultipartFormFileSection("xxxxxxxxxxxx", "lesson10.txt"));UnityWebRequest request = UnityWebRequest.Post("http://192.168.80.1:8080/httpServer/",data);request.SendWebRequest();while (!request.isDone){print(request.uploadProgress+" ; "+ request.uploadedBytes);yield return null;}print(request.uploadProgress + " ; " + request.uploadedBytes);if (request.result == UnityWebRequest.Result.Success){print("上传成功");//request.downloadHandler.data可以处理返回的信息}else{print("上传失败"+request.result+request.error);}}IEnumerator UpLoadPut(){UnityWebRequest request = UnityWebRequest.Put("http://192.168.80.1:8080/httpServer/", File.ReadAllBytes(Application.streamingAssetsPath + "/test.png"));request.SendWebRequest();while (!request.isDone){print(request.uploadProgress + " : " + request.uploadedBytes);yield return null;}print(request.uploadProgress + " : " + request.uploadedBytes);if (request.result == UnityWebRequest.Result.Success){print("上传成功");}}// Update is called once per framevoid Update(){}
}

单例模式,封装方法上传文件

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;public class NetWWWMgr : MonoBehaviour
{private static NetWWWMgr instance;public static NetWWWMgr Instance => instance;private string HTTP_SERVER_PATH = "http://192.168.80.1:8080/httpServer/";private void Awake(){instance = this;}/// <summary>/// 上传文件的方法/// </summary>/// <param name="fileName">上传上去的文件名</param>/// <param name="localPath">本地想要上传的文件路径</param>/// <param name="action">上传完成后的回调函数</param>public void UploadFile(string fileName, string localPath, UnityAction action = null){StartCoroutine(UploadFileAsync(fileName, localPath,action));}private IEnumerator UploadFileAsync(string fileName, string localPath, UnityAction action){ List<IMultipartFormSection> data = new List<IMultipartFormSection> ();data.Add(new MultipartFormFileSection(fileName, File.ReadAllBytes(localPath)));UnityWebRequest request = UnityWebRequest.Post(HTTP_SERVER_PATH, data);request.SendWebRequest();while (!request.isDone){print("上传进度:"+request.uploadProgress+" : "+request.uploadedBytes);yield return null;}print("上传进度:" + request.uploadProgress + " : " + request.uploadedBytes);if (request.result == UnityWebRequest.Result.Success){print("上传成功");action?.Invoke();}else{print("上传失败" + request.result + request.error);}}
}

高级操作

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor.Experimental.GraphView;
using UnityEditor.PackageManager.Requests;
using UnityEngine;
using UnityEngine.Networking;
public class CustomDownLoadFileHandler : DownloadHandlerScript
{//用于保存 本地存储时的路径private string savePath;private byte[] cachrBytes;private int index = 0;public CustomDownLoadFileHandler() : base(){ }public CustomDownLoadFileHandler(byte[] bytes): base(bytes){ }public CustomDownLoadFileHandler(string path) : base() { savePath = path;}protected override byte[] GetData(){return cachrBytes;}/// <summary>/// 从网络收到数据后,每帧会调用的方法/// </summary>/// <param name="data"></param>/// <param name="dataLength"></param>/// <returns></returns>protected override bool ReceiveData(byte[] data, int dataLength){Debug.Log("收到消息长度:" + dataLength);data.CopyTo(cachrBytes, index);index += dataLength;return true;}/// <summary>/// 从服务器收到Contenr-Length标头时会调用/// </summary>/// <param name="contentLength"></param>protected override void ReceiveContentLengthHeader(ulong contentLength){Debug.Log("收到数据长度:"+contentLength);//根据收到的标头 决定字节数组容器的大小cachrBytes = new byte[contentLength];}/// <summary>/// 消息收完后回调用的方法/// </summary>protected override void CompleteContent(){Debug.Log("消息收完");//把收到的字节数组 进行自定义处理 我们在这里存储到本地File.WriteAllBytes(savePath, cachrBytes);}
}
public class lesson10_6 : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){//高级操作指什么?// 在常用操作中我们使用的是 Unity 为我们封装好的一些方法// 我们可以方便的进行一些指定类型的数据获取// 比如// 下载数据时://1. 文本和二进制//2. 图片//3.AB 包// 如果我们想要获取其它类型的数据应该如何处理呢?// 上传数据时://1. 可以指定参数和值//2. 可以上传文件// 如果想要上传一些基于 HTTP 规则的其它数据应该如何处理呢?// 高级操作就是用来处理 常用操作不能完成的需求的// 它的核心思想就是: UnityWebRequest 中可以将数据处理分离开// 比如常规操作中我们用到的//DownloadHandlerTexture 和 DownloadHandlerAssetBundle 两个类// 就是用来将二进制字节数组转换成对应类型进行处理的// 所以高级操作时指 让你按照规则来实现更多的数据获取、上传等功能//关于UnityWebRequest的更多内容//1.构造函数UnityWebRequest request = new UnityWebRequest();//2.请求地址request.url = "服务器地址";//3.请求类型request.method = UnityWebRequest.kHttpVerbGET;//4.进度相关//request.downloadProgress;//request.uploadProgress//5.超时时间request.timeout = 50000;//6.上传下载字节数//request.uploadedBytes//request.downloadedBytes//7.重定向次数 设置为0标识不进行重定向  可以设置次数//request.redirectLimit = 0;//8.状态码 结果 错误内容//request.result;//request.responseCode;//request.error;//9.下载 上传处理对象//request.downloadHandler;//request.uploadHandler;//自定义获取数据 DownloadHandler 相关类// 关键类://1.DownloadHandlerBuffer 用于简单的数据存储,得到对应的二进制数据。//2.DownloadHandlerFile 用于下载文件并将文件保存到磁盘(内存占用少)。//3.DownloadHandlerTexture 用于下载图像。//4.DownloadHandlerAssetBundle 用于提取 AssetBundle。//5.DownloadHandlerAudioClip 用于下载音频文件。// 以上的这些类,其实就是 Unity 帮助我们实现好的,用于解析下载下来的数据的类// 使用对应的类处理下载数据,他们就会在内部将下载的数据处理为对应的类型,方便我们使用StartCoroutine(DownLoadTex());StartCoroutine(DownLoadAB());StartCoroutine(DownLoadAudioClip());//DownloadHandlerScript 是一个特殊类。就其本身而言,不会执行任何操作。// 但是,此类可由用户定义的类继承。此类接收来自 UnityWebRequest 系统的回调,// 然后可以使用这些回调在数据从网络到达时执行完全自定义的数据处理。StartCoroutine(DownLoadCustomHandler());}IEnumerator DownLoadTex(){UnityWebRequest request = new UnityWebRequest("http://192.168.80.1:8080/httpServer/lesson10.png");request.method= UnityWebRequest.kHttpVerbGET;//1.DownloadHandlerBuffer//DownloadHandlerBuffer handlerBuffer = new DownloadHandlerBuffer();//request.downloadHandler = handlerBuffer;//2.DownloadHandlerFile//DownloadHandlerFile  handlerFile = new DownloadHandlerFile(Application.persistentDataPath+"/downLoadfile.png");//request.downloadHandler = handlerFile;//3.DownloadHandlerTextureDownloadHandlerTexture handlerTexture = new DownloadHandlerTexture();request.downloadHandler = handlerTexture;yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.Success){//1.DownloadHandlerBuffer//获取字节数组//byte[] bytes = handlerBuffer.data;//3.DownloadHandlerTexture//Texture2D texture = handlerTexture.texture;}else{ }}IEnumerator DownLoadAB(){UnityWebRequest request = new UnityWebRequest("http://192.168.80.1:8080/httpServer/lua");request.method = UnityWebRequest.kHttpVerbGET;//第二个参数需要已知校检码 才能进行比较 检查完整性 如果不知道的话 只能传0 不进行完整性的检查//所有一般 只有进行AB包热更新时,服务器发送了对应的文件列表中包含了验证码才能进行检查DownloadHandlerAssetBundle downloadHandler = new DownloadHandlerAssetBundle(request.url,0);request.downloadHandler = downloadHandler;yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.Success){AssetBundle ab = downloadHandler.assetBundle;print(ab.name);}else{}}IEnumerator DownLoadAudioClip(){UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip("音效文件路径",AudioType.MPEG);yield return req.SendWebRequest();if (req.result == UnityWebRequest.Result.Success){AudioClip audioClip = DownloadHandlerAudioClip.GetContent(req);}else{}}IEnumerator DownLoadCustomHandler(){UnityWebRequest request = new UnityWebRequest();request.url = "http://192.168.80.1:8080/httpServer/xxx.png";request.method = UnityWebRequest.kHttpVerbGET;CustomDownLoadFileHandler customDownLoad = new CustomDownLoadFileHandler(Application.persistentDataPath + "/test.png");request.downloadHandler = customDownLoad;yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.Success){print("存储成功");}else{}}// Update is called once per framevoid Update(){}
}

自定义获取数据函数

    /// <summary>/// 通过UnityWebRequest获取数据/// </summary>/// <typeparam name="T"></typeparam>/// <param name="path">远端或本地地址</param>/// <param name="action">获取成功后的回调函数</param>/// <param name="localPath">如果下载本地 需要传第三个参数</param>/// <param name="type"> 如果下载音频切片需要第四个参数</param>public void UnityWebRequestLoad<T>(string path, UnityAction<T> action, string localPath = "", AudioType type = AudioType.MPEG) where T : class{StartCoroutine(UnityWebRequestLoadAsync<T>(path,action,localPath,type));}public IEnumerator UnityWebRequestLoadAsync<T>(string path, UnityAction<T> action, string localPath = "", AudioType type = AudioType.MPEG) where T : class{UnityWebRequest request = new UnityWebRequest(path, UnityWebRequest.kHttpVerbGET);if (typeof(T) == typeof(byte[]))request.downloadHandler = new DownloadHandlerBuffer();else if (typeof(T) == typeof(AssetBundle))request.downloadHandler = new DownloadHandlerAssetBundle(request.url, 0);else if (typeof(T) == typeof(Texture))request.downloadHandler = new DownloadHandlerTexture();else if (typeof(T) == typeof(object))request.downloadHandler = new DownloadHandlerFile(localPath);else if (typeof(T) == typeof(AudioClip))request = UnityWebRequestMultimedia.GetAudioClip(path, type);else{Debug.Log("未知类型"+typeof(T));yield break;}yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.Success){if (typeof(T) == typeof(byte[]))action?.Invoke(request.downloadHandler.data as T);else if (typeof(T) == typeof(AssetBundle))action?.Invoke((request.downloadHandler as DownloadHandlerAssetBundle).assetBundle as T);else if (typeof(T) == typeof(Texture))action?.Invoke((request.downloadHandler as DownloadHandlerTexture).texture as T);else if (typeof(T) == typeof(object))action?.Invoke(null);else if (typeof(T) == typeof(AudioClip))action?.Invoke( DownloadHandlerAudioClip.GetContent(request) as T);}else{print("下载失败" + request.result + request.error);}}

http://www.dtcms.com/a/469627.html

相关文章:

  • Java后端开发核心技术选型指南(优化版)
  • 数字图像处理-图像的傅里叶变换
  • 分布式缓存架构:从原理到生产实践
  • 现代计算机视觉任务综合概述:定义、方法与应用
  • ai 作物分类
  • sm2025 模拟赛11 (2025.10.7)
  • WebSocket 是什么原理?为什么可以实现持久连接?
  • 【开题答辩全过程】以 宝成花园物业管理系统为例,包含答辩的问题和答案
  • CORS配置实战:SpringBoot与Vite项目的本地联调解决方案
  • 长沙学做网站建设wordpress图片全部压缩
  • [cpprestsdk] 统一资源标识符 | uri_builder
  • 网站开发与运维收费明细报社网站开发做什么
  • 徐州做网站的公司招聘可以做ppt的网站或软件
  • python自带的unittest框架
  • STM32学习记录-0.1 STM32外设
  • 人形机器人:Tesla Optimus的AI集成细节
  • starocks创建表后还需要设置什么
  • 《操作系统真象还原》 第十章 输入输出系统
  • 免费发布信息的网站网站建设规划文档
  • kali安装ARL-docker灯塔
  • Linux的Dynamic debug功能
  • 需要做网站建设的公司做流程图用什么网站
  • 常用的日期时间处理库Day.js和Moment.js
  • Verilog和FPGA的自学笔记5——三八译码器(case语句与锁存器)
  • Mpi多机通信环境搭建(2台机器)
  • 简述网站制作流程图如何免费注册淘宝店铺
  • 人工智能在数学教育中的应用 | 现状、探索与实践
  • VSCode括号高亮插件(vscode插件)bracket pair、活动括号对、括号线(未完全检查)
  • FPGA强化-串口rs232
  • 为何建设银行网站无法登陆公司官网开发