1、代码实现
using UnityEngine;
using System.Collections;using System;using System.Text;using System.Net;using System.IO; internal class WebReqState{ public byte[] Buffer;public FileStream fs;
public const int BufferSize = 1024;
public Stream OrginalStream;
public HttpWebResponse WebResponse;
public WebReqState(string path)
{ Buffer = new byte[1024]; fs = new FileStream(path, FileMode.Create); }}
public class HttpHelper
{string path = null;
string assetName; public HttpHelper(string path) { this.path = path; }public void AsyDownLoad(string url)
{ Debug.Log("url is:+"+url); assetName = url.Split('/')[4]; Debug.Log("assetName is :+"+assetName); HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), httpRequest); }void ResponseCallback(IAsyncResult ar)
{ HttpWebRequest req = ar.AsyncState as HttpWebRequest; if (req == null) return; HttpWebResponse response = req.EndGetResponse(ar) as HttpWebResponse; if (response.StatusCode != HttpStatusCode.OK) { response.Close(); return; } Debug.Log(path + "/" + assetName); WebReqState st = new WebReqState(path + "/" + assetName); st.WebResponse = response; Stream responseStream = response.GetResponseStream(); st.OrginalStream = responseStream; responseStream.BeginRead(st.Buffer, 0, WebReqState.BufferSize, new AsyncCallback(ReadDataCallback), st); }void ReadDataCallback(IAsyncResult ar)
{ WebReqState rs = ar.AsyncState as WebReqState; int read = rs.OrginalStream.EndRead(ar); if (read > 0) { rs.fs.Write(rs.Buffer, 0, read); rs.fs.Flush(); rs.OrginalStream.BeginRead(rs.Buffer, 0, WebReqState.BufferSize, new AsyncCallback(ReadDataCallback), rs); } else { rs.fs.Close(); rs.OrginalStream.Close(); rs.WebResponse.Close(); Debug.Log(assetName + ":::: success"); } }}
2、从服务器上下载资源 到本地上(PC端经测试成功)
void OnGUI()
{ string[] str = new string[2] { "Sphere", "Cube" }; //下载 if (GUI.Button(new Rect(10, 10, 200, 45), "下载")) { string rootPath = Application.persistentDataPath;//android上保存到 /storage/sdcard0/Android/data/包名(例如:com.example.test)/files for (int i = 0; i < str.Length; i++) //str是string型数组,存放部分assetbundle名字 { Thread thread = new Thread(new ParameterizedThreadStart(DownAsset)); //ParameterizedThreadStart 多线程传参 thread.Start(rootPath + "|" + str[i]); //只能带一个object参数 所以使用字符串拼接 } }
void DownAsset(System.Object file)
{ string[] fileName = file.ToString().Split('|'); Debug.Log("文件名000000是:+" + fileName[0]); Debug.Log("文件名是1111:+" + fileName[1]); HttpHelper help = new HttpHelper(fileName[0]); help.AsyDownLoad("http://192.168.0.98/MyItems/Test/" + fileName[1] + ".assetbundle");//注意在手机上测试 该对Ip地址 Debug.Log("下载的地址是:+" + "http://192.168.0.98/MyItems/Test/" + fileName[1] + ".assetbundle");}