互联网发展到现在,很多技术已经很成熟了,但是用到unity在某一个特定平台下没问题,如果跨平台就有问题了。就拿http通信来说,C#原生的http到hololens上就不好使,我只能用unitywebRequst。以下是两种方式的文件下载,写法都差不多。
一、HttpWebRequst请求方式
//下载地址
private const string url = "http://127.0.0.1:3000/api/";
//解压完成事件
internal static event Action OnUnZipCompletedEvent;
//下载完成事件
internal static event Action OnDownloadCompleteEvent;
/// <summary>
/// 下载
/// </summary>
/// <param name="downloadfileName">下载的文件名</param>
/// <param name="desFileName">本地存储地址</param>
/// <returns></returns>
public static IEnumerator DownLoad(string downloadfileName, string desFileName)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(downloadfileName);
request.Timeout = 5000;
WebResponse response = request.GetResponse();
using (FileStream fs = new FileStream(desFileName, FileMode.Create))
using (Stream netStream = response.GetResponseStream())
{
int packLength = 1024 * 20;
long countLength = response.ContentLength;
byte[] nbytes = new byte[packLength];
int nReadSize = 0;
nReadSize = netStream.Read(nbytes, 0, packLength);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = netStream.Read(nbytes, 0, packLength);
double dDownloadedLength = fs.Length * 1.0 / (1024 * 1024);
double dTotalLength = countLength * 1.0 / (1024 * 1024);
string ss = string.Format("已下载 {0:F}M / {1:F}M", dDownloadedLength, dTotalLength);
Debug.Log(ss);
yield return false;
}
netStream.Close();
fs.Close();
if (OnDownloadCompleteEvent != null)
{
Debug.Log("download finished");
OnDownloadCompleteEvent.Invoke();
}
}
}
二、UnityWebRequst请求方式
internal static event Action<string> OnDownloadProgressEvent;
public static IEnumerator DownLoad(string desFileName)
{
string url1 = url + "download?fileName=data.zip&tempFileName=data.zip";
if (!File.Exists(desFileName))
{
UnityWebRequest request = UnityWebRequest.Get(url1);
yield return request.Send();
if (request.isDone)
{
int packLength = 1024 * 20;
byte[] data = request.downloadHandler.data;
int nReadSize = 0;
byte[] nbytes = new byte[packLength];
using (FileStream fs = new FileStream(desFileName, FileMode.Create))
using (Stream netStream = new MemoryStream(data))
{
nReadSize = netStream.Read(nbytes, 0, packLength);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = netStream.Read(nbytes, 0, packLength);
double dDownloadedLength = fs.Length * 1.0 / (1024 * 1024);
double dTotalLength = data.Length * 1.0 / (1024 * 1024);
string ss = string.Format("已下载 {0:F}M / {1:F}M", dDownloadedLength, dTotalLength);
if(OnDownloadProgressEvent!=null)
{
OnDownloadProgressEvent.Invoke(ss);
}
Debug.Log(ss);
yield return null;
}
}
}
}
if (OnDownloadCompleteEvent != null)
{
Debug.Log("download finished");
OnDownloadCompleteEvent.Invoke();
}
}
无论哪种方式,都会遵循http请求规则