Unity3d C# HttpWebRequest 异步下载文件

最近一直在把公司游戏迁移到支持ARM64,中间出现了很多BUG或者Unity目前不支持操作的问题,这两天遇到异步HttpWebRequest不支持的问题,因为之前一直没有接触,所以也趁机学习了下相关使用。

下面通过一个例子,来使用HttpWebRequest异步下载一个ZIP文件。

using UnityEngine;
using System.Collections;
using System.Net;
using System.IO;
using System;
using System.Threading;
using System.Text;

public class RequestState
{
    const int m_buffetSize = 1024;
    public StringBuilder m_requestData;
    public byte[] m_bufferRead;
    public HttpWebRequest m_request;
    public HttpWebResponse m_response;
    public Stream m_streamResponse;

    public RequestState()
    {
        m_bufferRead = new byte[m_buffetSize];
        m_requestData = new StringBuilder("");
        m_request = null;
        m_streamResponse = null;
    }
}

public class NewBehaviourScript : MonoBehaviour {

    FileStream fileStream=null;

	// Use this for initialization
	void Start ()
    {
        fileStream = new FileStream("disunity_v0.3.4.zip", FileMode.Create);

        DownloadMusicAsyn();
	}

    void DownloadMusicAsyn()
    {
        Debug.Log("DownloadMusicAsyn Thread Start");

        try
        {

            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://dev.thisisgame.com.cn/disunity_v0.3.4.zip");

            RequestState myRequestState = new RequestState();
            myRequestState.m_request = myHttpWebRequest;

            Debug.Log("BeginGetResponse Start");
            //异步获取;
            IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

            Debug.Log("BeginGetResponse End");
        }
        catch (System.Exception ex)
        {
            Debug.LogError(ex.ToString());
        }

    }

    void RespCallback(IAsyncResult result)
    {
        Debug.Log("RespCallback 0");

        try
        {
            RequestState myRequestState = (RequestState)result.AsyncState;
            HttpWebRequest myHttpWebRequest = myRequestState.m_request;

            Debug.Log("RespCallback EndGetResponse");
            myRequestState.m_response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(result);

            Stream responseStream = myRequestState.m_response.GetResponseStream();
            myRequestState.m_streamResponse = responseStream;

            //开始读取数据;
            IAsyncResult asyncreadresult = responseStream.BeginRead(myRequestState.m_bufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState);

            return;
        }
        catch (System.Exception ex)
        {
            Debug.LogError(ex.ToString());
        }
    }

    void ReadCallBack(IAsyncResult result)
    {
        Debug.Log("ReadCallBack");
        try
        {
            RequestState myRequestState = (RequestState)result.AsyncState;
            Stream responseStream = myRequestState.m_streamResponse;
            int read = responseStream.EndRead(result);

            Debug.Log("read size =" + read);

            if (read > 0)
            {
                //将接收的数据写入;
                fileStream.Write(myRequestState.m_bufferRead, 0, 1024);
                fileStream.Flush();
                //fileStream.Close();

                //继续读取数据;
                myRequestState.m_bufferRead = new byte[1024];
                IAsyncResult asyncreadresult = responseStream.BeginRead(myRequestState.m_bufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState);
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError(ex.ToString());
        }
    }

    void TimeoutCallback(object state, bool timeout)
    {
        if (timeout)
        {
            HttpWebRequest request = state as HttpWebRequest;
            if (request!=null)
            {
                request.Abort();
            }

        }
    }

	// Update is called once per frame
	void Update () {

	}
}
时间: 2024-08-28 14:51:58

Unity3d C# HttpWebRequest 异步下载文件的相关文章

android开发步步为营之67:使用android开源项目android-async-http异步下载文件

android-async-http项目地址 https://github.com/loopj/android-async-http,android-async-http顾名思义是异步的http请求,不过它也支持同步请求的,本文主要使用了android-async-http做异步请求下载文件.每当app需要更新新版本的时候,就需要用到下载功能的,经研究android-async-http这个第三方开源项目还是挺好用的,这里介绍给大家.     1.下载类DownloadManager.java

js异步下载文件请求

注意 :通常下载文件是用get请求 window.location.href=url; 但是 我们需要下载完成监听,所以必须要异步执行.用常规的ajax是不可以的.我们要用blob对象来实现1.原生的如何实现 function loadDown(query) { var url = "${ctx}/bill/billExport"+query; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true);    // 也可以使用

WebClient异步下载文件

namespace ConsoleAppSyncDownload{    class Program    { static void Main(string[] args)        {            WebClient webClient = new WebClient();            //Console.Write("输入下载文件地址:");            //var s = Console.ReadLine();            Conso

ajax异步下载文件

ajax不支持异步下载,但我想你是不想让地址栏发生跳转,如果是这样的话,我到是有几种方法.这几种方法的原理都是一样的,就是发送同步请求,当同步请求下载东西是并不会改变url <a href="你要下载的资源的url">下载</a> document.href="你要下载的资源的url" var form = $("<form action='你要下载的资源的url' method='post'></form>

Unity3d C# Socket 下载文件 (同步到)

续篇 Unity3d C# HttpWebRequest 异步下载文件 ,由于project编译为IL2CPP的情况下仍然无效.提示HttpWebrequest 在当前版本号不支持.所以还是寻求其他的办法. 正好分公司的同事也碰到了下载文件的BUG,可是他们是仅仅可下面载一部分,好歹也比我的情况好,于是借同事的參考咯. 结构大致是用Socket 向server发送Http请求.再设置各种Http头,然后接收server发来的数据流. 先了解下Http头: 典型的请求消息: GET http://

Unity3d C# Socket 下载文件 (同步向)

接上篇 Unity3d C# HttpWebRequest 异步下载文件 ,因为在将工程编译为IL2CPP的情况下仍然无效,提示HttpWebrequest 在当前版本不支持,所以还是寻求其它的办法. 正好分公司的同事也碰到了下载文件的BUG,但是他们是只能够下载一部分,好歹也比我的情况好,于是借同事的参考咯. 结构大致是用Socket 向服务器发送Http请求,再设置各种Http头,然后接收服务器发来的数据流. 先了解下Http头: 典型的请求消息: GET http://download.m

C#使用BeginInvoke和EndInvoke异步下载和获取返回结果

场景:为了防止UI卡死,使用异步下载文件 问题:采用多线程下载,关闭窗口后下载线程不能停止,线程操作麻烦. 参考:C#客户端的异步操作: http://www.cnblogs.com/fish-li/archive/2011/10/23/2222013.html 方案:采用BeginInvoke的方式调用下载方法,委托会自动启动新线程,停止时也不需要手动控制.使用EndInvoke获取返回结果. try { IAsyncResult ir = process.BeginInvoke(new Ht

unity下载文件三(http异步下载)

异步下载,顾名思义就是不影响你主线程使用客户端的时候,人家在后台搞你的明堂. 直接入主题,既然要下载,首先得请求,请求成功之后进行回调,这就是一个异步过程,异步回调的时间不可控. 1.首先请求下载. public bool DownLoadFile(DownLoadFileModel file) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.1.1:8080/" +

winform自动更新并实现文件的批量异步下载

public partial class update : Form    {        private WebClient client;        int downfilenum = 0; //已下载文件数        int downlistnum = 0;//总下载文件数        List<string> list;        private string URl;        private string fileName;        private con