您的位置:首页 > 理论基础 > 计算机网络

Unity实现网络多线程上传数据,支持断点续传

2018-03-16 10:17 519 查看
在现在的网络游戏中,网络层面的交互是不可或缺的模块了, 其中本地数据上传至服务器的需求几乎是游戏的基本配置了 , 最近在用Unity做一款应用(不是游戏),其中涉及到数据上传 , 在根据C#语言进行方法封装, 发现还挺好用 , 代码不多 ,这里给大家分享一下.

支持断点续传开关判断

本地数据校验

图片链接和图片上传

核心代码 ↓

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

/// <summary>
/// 多线程可断点下载( 需服务器支持 )
/// </summary>
public class Download
{
public const int TIMEOUT = 100000;
public float progress { get; private set; }
public bool isDone { get; private set; }
private bool isstop;
public bool isStop {
get { return isstop; }
set { if (value) { thread.Abort(); thread = null; } isstop = value; }
}
private Thread thread;

/// <summary>
/// Initializes a new instance of the <see cref="T:Download"/> cla
4000
ss.
/// </summary>
/// <param name="url">URL.</param>
/// <param name="desDir">DES dir.</param>
/// <param name="isSupportResume">If set to <c>true</c> 支持断点续传.</param>
/// <param name="callback">Callback.</param>
public Download(string url, string desDir, bool isSupportResume, System.Action callback)
{
thread = new Thread(new ThreadStart(delegate {
using (FileStream fs = new FileStream(desDir, isSupportResume ? FileMode.OpenOrCreate : FileMode.Create)) {
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
req.Method = "HEAD";
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
var len = resp.ContentLength;
long fileLen = fs.Length;
if (fs.Length < len) {
fs.Seek(fs.Length, SeekOrigin.Begin);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = TIMEOUT;
request.Method = "GET";
request.AddRange((int)fs.Length);
var response = request.GetResponse() as HttpWebResponse;
using (Stream stream = response.GetResponseStream()) {
byte[] buffer = new byte[1024];
int lenth = stream.Read(buffer, 0, buffer.Length);
while (lenth > 0) {
if (isStop) break;
fs.Write(buffer, 0, lenth);
fileLen += lenth;
//todo 计算进度
progress = (float)fileLen / len;
lenth = stream.Read(buffer, 0, buffer.Length);
if (lenth < 1024) {
Debug.Log(lenth);
}
}
Debug.Log(">>>>>>>>>");
}
} else {
progress = 1;
}
}
if (progress == 1 && callback != null) {
callback();
}
}));
thread.Start();
}
}


使用方法 ↓

using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Test.
/// </summary>
public class Test : MonoBehaviour
{
string url = @"http://attachments.gfan.com/forum/201508/17/1046319ijbj4whiw9itrmm.png";

string filePath = null;
[SerializeField]
public Slider slider;
Download down = null;

void Start()
{
filePath = @Application.dataPath + "/123.png";
down = new Download(url, filePath, true, () => print("下载完毕"));
}

void Update()
{
slider.value = down.progress;
}

private void OnDestroy()
{
if (down != null) {
down.isStop = true;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐